首页 文章

UIButton文本仅在触摸时出现

提问于
浏览
2

我按如下方式设置了一个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)

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

1 回答

  • 3

    您的按钮很可能是在辅助线程上绘制的 . 所以它不会在合适的时间绘制 .

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

    您可以使用以下代码实现此目的:

    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
    }
    

相关问题