【发布时间】:2018-02-22 16:22:28
【问题描述】:
我正在尝试以编程方式创建一个以指定超级视图为中心的视图。我几乎可以实现这种行为,但是居中视图不尊重其内容的动态高度。这是我为实现它而创建的函数:
static func overlayWithButton(onView view: UIView, buttonText: String, theme: Theme = .dark, action: Action? = nil) -> UIView {
// create overlay
let overlay = UIView()
overlay.translatesAutoresizingMaskIntoConstraints = false
let leftInset: CGFloat = 20
let rightInset: CGFloat = 20
// Style overlay
overlay.backgroundColor = theme == .dark ? UIColor.black : UIColor.white
overlay.alpha = 0.75
overlay.cornerRadius = 10
// create button
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
button.translatesAutoresizingMaskIntoConstraints = false
// Style Button
button.backgroundColor = UIColor.clear
button.setTitle(buttonText, for: .normal)
button.setTitleColor(theme == .dark ? lightBlueButtonText : UIColor.black, for: .normal)
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.titleLabel?.numberOfLines = 0
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
button.isEnabled = true
// add button action
if let action = action {
button.add(for: .touchUpInside, action)
}
// add constraints
overlay.addSubview(button)
button.centerXAnchor.constraint(equalTo: overlay.centerXAnchor).isActive = true
button.leftAnchor.constraint(greaterThanOrEqualTo: overlay.leftAnchor).isActive = true
button.rightAnchor.constraint(lessThanOrEqualTo: overlay.rightAnchor).isActive = true
button.topAnchor.constraint(equalTo: overlay.topAnchor).isActive = true
button.bottomAnchor.constraint(equalTo: overlay.bottomAnchor).isActive = true
view.addSubview(overlay)
overlay.leftAnchor.constraint(equalTo: view.leftAnchor, constant: leftInset).isActive = true
overlay.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -rightInset).isActive = true
overlay.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
return overlay
}
这适用于短按钮标题: 但是,对于较长的标题,按钮内容会被剪裁: 使用显示我可以看到标题/按钮标签按预期响应。 我已经有一段时间了,我无法让居中的叠加层扩展其高度以匹配其内容的内在内容大小。有什么想法吗?
【问题讨论】:
-
你能否将叠加层的高度锚设置为按钮的高度锚?
-
如果我这样做而不是顶部/底部锚点,我会得到相同的结果,如果我这样做除了顶部/底部锚点之外,也会得到相同的结果。
-
我怀疑这与 translatesAutoResizingMaskIntoContraints 摆脱了 UIButton 的固有内容大小有关,但我需要将其设置为 true,否则应用于按钮的所有其他约束都不会'不行。
-
你在打电话给
setNeedsLayout和layoutIfNeeded吗? -
我应该在哪里打这些电话?
标签: ios swift user-interface autolayout constraints