Cristian Alonso
Cristian Alonso

Reputation: 45

UIButton Text Only Appearing On Touch

I've set up a UIButton as follows:

let scanButton = UIButton()

func setUpScanButton (scanButton: UIButton) -> () {
    scanButton.addTarget(self, action: "goToScanner" , forControlEvents: UIControlEvents.TouchUpInside)
    scanButton.backgroundColor = UIColor.greenColor()
    scanButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
    scanButton.setTitle("Scan", forState: UIControlState.Normal)
    scanButton.frame = CGRectMake(36, 385, self.view.frame.width - 41, 30)
    scanButton.center.x = CGRectGetMidX(self.view.bounds)
    scanButton.center.y = CGRectGetMidY(self.view.bounds)
    scanButton.layer.cornerRadius = 6
    self.view.addSubview(scanButton)
}
setUpScanButton(scanButton)

The issue is that the text does not appear until the touch is applied to the button. I tried editing the color of both the text and the button but to no avail.

Upvotes: 2

Views: 903

Answers (1)

The Tom
The Tom

Reputation: 2810

Your button is most probably drawn on a secondary thread. So it won't be drawn at the right time.

To be correctly drawn and at the right time, all UI elements have to be drawn on the main thread.

You can achieve that with the following code:

dispatch_async(dispatch_get_main_queue(), {
    // Insert your code to add the button here
})

In Swift 3 & 4:

DispatchQueue.main.async {
    // Insert your code to add the button here
}

Upvotes: 4

Related Questions