Trouble left-aligning UIButton title (iOS/Swift)
Asked Answered
I

2

45

I'm having a problem left-aligning a UIButton's text. I also tried changing it to .Right but it still stays centered. I also tried aButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0) instead of aButton.titleLabel?.textAlignment = .Left but that doesn't change anything either. Is there an alternative way to programmatically change the alignment of a UIButton title's?

        allButtonViews = UIView(frame: CGRectMake(0, 44, 100, 100))
        allButtonViews.backgroundColor = .redColor()

        let campusButton = UIButton(type: UIButtonType.System) as UIButton
        aButton.frame = CGRectMake(0, 0, 300, 70)
        aButton.setTitle("A", forState: .Normal)
        aButton.titleLabel?.textColor = .blueColor()
        aButton.titleLabel?.textAlignment = .Left
        aButton.backgroundColor = .whiteColor()

        sortView.addSubview(aButton)
        view.addSubview(allButtonViews)

enter image description here

Intercom answered 7/4, 2016 at 0:36 Comment(0)
D
162

Try this:

button.contentHorizontalAlignment = .left
Dominy answered 7/4, 2016 at 0:48 Comment(3)
Is there any setting in Xcode that would enable same functionality?Partheniaparthenocarpy
Add a user-defined runtime attribute with contentHorizontalAlignment as an NSNumber with value of 0-3 for center, left, right, and fill.Clandestine
.Left has been renamed => .left.Thora
G
21

Updated for Swift 3 or Swift 4

yourButton.contentHorizontalAlignment = .left
Goyette answered 9/8, 2017 at 9:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.