【问题标题】:Swift UIButton not appearing on screenSwift UIButton 没有出现在屏幕上
【发布时间】:2016-06-02 12:28:37
【问题描述】:

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

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!) {

}

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

【问题讨论】:

  • 尝试为您的 UIButton 添加背景颜色,并为其标题添加色调
  • 谢谢,这就是问题所在!不知何故,标题和按钮都是白色的
  • 我最近看到一个类似的问题,我认为这是我们以编程方式创建UIButton时的默认颜色

标签: swift uibutton


【解决方案1】:

为您的UIButton 添加背景颜色并为标题添加淡色。这将解决问题

【讨论】:

    【解决方案2】:

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

    viewDidLoad 中的框架设置不正确。尽可能早地使用方法viewDidLayoutSubviews 为 ViewController 正确设置框架。

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

    【讨论】:

      【解决方案3】:

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

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

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

      例如: 斯威夫特 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)
      }
      

      【讨论】:

        【解决方案4】:

        您可以重新检查情节提要中的按钮属性,它没有隐藏

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多