ios - UIButton 文本仅在触摸时出现

标签 ios swift uibutton

我设置了一个 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
}

关于ios - UIButton 文本仅在触摸时出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30542713/

相关文章:

ios - TouchDown 上的自定义 UIButton

ios - 不想按排序顺序对参数进行排序 alamofire

ios - 如何使用滑动 Action 移动带有动画的 tableViewCell 中的单元格

ios - NSUserDefaults 不保存数据 Objective C

ios - 如何解决官方 iOS 应用程序开发教程中的自动布局问题?

ios - 如何在我的iOS Xing App中深度链接到个人资料?

swift - 如何使用 POST 方法 swift 在 header 字段中传递 token

iphone - 使固定大小的圆形按钮作为iPhone SDK中的图像

ios - 如何使用 Swift 隐藏/显示 View Controller 中的按钮?

UIButton 上的 iOS NSAttributedString