【问题标题】:UIButton, Autolayout and getting the height of the buttonUIButton,自动布局和获取按钮的高度
【发布时间】:2016-01-06 15:50:06
【问题描述】:

我正在尝试获取自定义 UIButton 的真实高度。但我总是得到一个比我预期的要小得多的值。我得到了大约 30 的结果,但预计大约是 45。

override func awakeFromNib() {
  print(self.frame.height)
  self.layer.cornerRadius = self.layout.frame.height / 2.0
  self.clipsToBounds = true
  self.titleLabel?.adjustsFontSizeToFitWidth = true
}

这是我的代码,但在运行时自动布局会以某种方式改变大小,这是完美的,但我无法设置正确的cornerRadius(总是太小)。所以也许我需要乘数或类似的东西。我已经通过添加 top 和 bottom 的 contentEdgeInsets 进行测试,但没有任何区别。

谢谢 托比亚斯

【问题讨论】:

    标签: ios swift uibutton autolayout


    【解决方案1】:

    视图尚未在awakeFromNib() 中布局。当布局保证已经发生时,设置你的拐角半径。

    查看:

    override func layoutSubviews() {
      super.layoutSubviews()
      layer.cornerRadius = frame.height / 2.0
    }
    

    对于 UIViewController:

    override func viewDidLayoutSubviews() {
      super.viewDidLayoutSubviews()
      view.layer.cornerRadius = view.frame.height / 2.0
    }
    

    【讨论】:

      【解决方案2】:

      在打印尺寸之前尝试调用 self.layoutIfNeeded()

      【讨论】:

      • 也许你在父视图中调用 layoutIfNeeded()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2020-01-14
      • 2014-07-13
      相关资源
      最近更新 更多