简体   繁体   中英

Text does not appear on UIButton in swift

Pounding my head against this. Should be so simple.

Running in a playground inside MyClass:

func configureButton(){
    let btn: UIButton = UIButton(frame: CGRectMake(5, 75, 90, 20))
    btn.backgroundColor = UIColor.greenColor()
    btn.addTarget(self,
                  action: #selector(MyClass.buttonTapped),
                  forControlEvents: UIControlEvents.TouchUpInside)
    addSubview(btn)
    btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
    btn.titleLabel?.font = UIFont(name: "Helvetica", size: 40)
    btn.titleLabel?.text = "tap me"
  }

The button shows up green, and works when pressed, but does not display the text.

This line is just wrong:

btn.titleLabel?.text = "tap me"

Do not attempt to manipulate the button's title label text directly like this. Always pass through the button's official title setter, setTitle:forState: .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM