【问题标题】:Centering a button in UIScrollView在 UIScrollView 中居中按钮
【发布时间】:2017-11-14 16:55:45
【问题描述】:

对于我的生活,我不知道如何将UIButton 居中在UIScrollView...

let sv = UIScrollView(frame: CGRect(x: 0, y: 0, width: 300, height: 600))
let b = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
sv.addSubview(b)
b.center = sv.center

无论我做什么,按钮似乎都偏离了中心。这个逻辑在正常UIView 下工作。为什么不用UIScrollView

【问题讨论】:

  • 为什么不直接放在UIView的中心呢?它总是在中心。
  • 问题是我需要按钮的 y 位置在滚动视图中的所有内容之后,但仍居中。

标签: ios swift uiscrollview uibutton uikit


【解决方案1】:

你也可以使用

let b = UIButton(frame: CGRect(x: sv.frame.size.width/2 -15, y: sv.frame.size.height/2 -15, width: 30, height: 30))

对于您的代码,首先检查 sv.center 的值,如果没问题并且您的 UI 没有更新,则调用 layoutIfneeded

参考:How is layoutIfNeeded used?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 2023-04-10
    • 2012-07-28
    相关资源
    最近更新 更多