UIButton 文本仅在触摸时出现

UIButton Text Only Appearing On Touch

我按如下方式设置了一个 UIButton:

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)

问题是在对按钮应用触摸之前,文本不会出现。我尝试编辑文本和按钮的颜色,但无济于事。

您的按钮很可能是在辅助线程上绘制的。所以不会在合适的时候画出来

要在正确的时间正确绘制,所有 UI 个元素都必须在主线程上绘制。

您可以使用以下代码实现:

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

在 Swift 3 & 4:

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