Andrey M.
Andrey M.

Reputation: 3069

UIButton label not showing

I have the following code

let width = UIScreen.mainScreen().bounds.width    
let linkLabel = UILabel(frame: CGRect(x: 8, y: contentHeight, width: 100, height: labelHeight))
    let linkButton = UIButton(frame: CGRect(x: 108, y: contentHeight, width: width - 108, height: labelHeight))
    mainScrollView.addSubview(linkLabel)
    mainScrollView.addSubview(linkButton)
    linkLabel.text = "Link:"
    linkButton.addTarget(self, action: #selector(linkButtonPressed), forControlEvents: .TouchUpInside)
    linkButton.setTitle("http://example.com", forState: .Normal)
    linkButton.layer.borderWidth = 1.0

    mainScrollView.contentSize = CGSize(width: view.frame.width, height: contentHeight)

And when view loads i see the following picture (Note that button is black rectangle): enter image description here

So title is not visible but when i click on the button i can fetch its title property

func linkButtonPressed(sender: UIButton) {
    print("button title = \(sender.titleLabel?.text)")
}

And i get the button title = Optional("http://example.com") but anyway button title is not visible. Any suggestions?

Upvotes: 3

Views: 3117

Answers (2)

Mudith Chathuranga Silva
Mudith Chathuranga Silva

Reputation: 7434

You skipped one step. You should add title color :-

linkButton.setTitleColor(UIColor.blackColor(), forState: .Normal)

Upvotes: 4

Bhumika
Bhumika

Reputation: 876

Your button title is display but in white color.Give any color to button title it is there.There is no problem in your code.

linkButton.setTitle("http://example.com", forState: .Normal)
linkButton.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)

Upvotes: 6

Related Questions