Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble left-aligning UIButton title (iOS/Swift)

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

like image 452
stumped Avatar asked Apr 07 '16 00:04

stumped


2 Answers

Try this:

button.contentHorizontalAlignment = .left
like image 163
OhNo Avatar answered Nov 18 '22 02:11

OhNo


Updated for Swift 3 or Swift 4

yourButton.contentHorizontalAlignment = .left
like image 20
iAj Avatar answered Nov 18 '22 02:11

iAj