1

I creating UIButton like that:

okBtn = UIButton()
okBtn.setTitle("OK", for: .normal)
okBtn.setTitle("OK", for: .selected)
okBtn.titleLabel?.textColor = .purpleLight
okBtn.backgroundColor = .red
okBtn.addTarget(self, action: #selector(didTapOKBtn), for: .touchUpInside)
self.addSubview(okBtn)

However, color is not setted, i added a screen to show how it looks.

enter image description here

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107

3 Answers3

2

Use title color

okBtn.setTitleColor(UIColor.blue, for: UIControlState.normal)
Abhishek Jain
  • 4,557
  • 2
  • 32
  • 31
1

Use frame as required & add to your view as -

   override func viewDidLoad() {
    super.viewDidLoad()
    let okBtn = UIButton(frame: CGRect(x: 20, y: 70, width: 50, height: 50))
    okBtn.setTitle("OK", for: .normal)
    okBtn.backgroundColor = .red
    okBtn.setTitleColor(.white, for: .normal)
    view.addSubview(okBtn)
}
Jack
  • 13,571
  • 6
  • 76
  • 98
1

Set the frame size first.

    okBtn = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100)) //Sets the frame size on your viewController
    okBtn.setTitle("OK", for: .normal)
    okBtn.setTitleColor(UIColor.purple, for: .normal) //Sets the color of the text on the button
    //There is no color as purpleLight. You need to set the rgb to get your desired color.
    okBtn.backgroundColor = .red
    okBtn.addTarget(self, action: #selector(didTapOKBtn), for: .touchUpInside)
    self.view.addSubview(okBtn)
amish
  • 335
  • 4
  • 17