44

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

stumped
  • 3,235
  • 7
  • 43
  • 76

2 Answers2

157

Try this:

button.contentHorizontalAlignment = .left
Naresh
  • 16,698
  • 6
  • 112
  • 113
OhNo
  • 1,720
  • 1
  • 11
  • 7
21

Updated for Swift 3 or Swift 4

yourButton.contentHorizontalAlignment = .left
iAj
  • 3,787
  • 1
  • 31
  • 34