Swift UIButton没有出现在屏幕上

时间:2016-06-02 12:28:37

标签: swift uibutton

我的tabbar控制器中有一个视图,我想显示一个按钮。我根据条件以编程方式创建此按钮,因此我使用以下代码但没有出现任何内容:

override func viewDidLoad() {
    super.viewDidLoad()
    if !Settings.getIsConnected() {
        notConnected()
    }
}

func notConnected() {
    let connectBtn = UIButton(frame: CGRect(x: self.view.center.x, y: self.view.center.y, width: 200, height: 45))
    connectBtn.setTitle("Connect", forState: .Normal)
    connectBtn.addTarget(self, action:#selector(self.pressedConnect(_:)), forControlEvents: .TouchUpInside)
    self.view.addSubview(connectBtn)

    print("Button created")
}

func pressedConnect(sender: UIButton!) {

}

我对自己做错了什么一无所知。有人有建议吗?因为它会打印出“按钮创建”,所以它肯定会在noConnected()方法中运行代码。

4 个答案:

答案 0 :(得分:5)

UIButton添加背景颜色,并为标题添加色调。这将解决问题

答案 1 :(得分:3)

尝试将代码移至viewDidAppear并查看按钮是否显示。

viewDidLoad中时未正确设置框架。使用方法viewDidLayoutSubviews可以在为ViewController正确设置框架的最早时间内使用。

通过此代码更改,您需要一些额外的逻辑,以便将按钮添加为子视图时。

答案 2 :(得分:1)

由于更多原因,可能无法显示以编程方式创建的按钮,例如:

  • 未设置色彩
  • 未设置背景色
  • 该按钮未添加到视图层次结构中
  • 按钮被隐藏

在这种情况下,您应该更改按钮的颜色或背景色。

例如: Swift 4.2:

private lazy var connectButton: UIButton = {
    let button = UIButton(type: .custom)
    button.backgroundColor = .green
    button.setTitleColor(.black, for: .normal)
    button.setTitle(NSLocalizedString("Connect", comment: ""), for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    return button
}()

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(connectButton)
}

答案 3 :(得分:0)

您可以重新检查故事板中 隐藏 的按钮属性

相关问题