我正在尝试以编程方式创建一个以指定 super View 为中心的 View 。我几乎可以实现这种行为,但是居中 View 不尊重其内容的动态高度。这是我为实现它而创建的函数:
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
}
这适用于短按钮标题: 但是,对于较长的标题,按钮内容会被剪裁: 使用显示我可以看到标题/按钮标签按预期响应。 我已经有一段时间了,我无法让居中的叠加层扩展其高度以匹配其内容的内在内容大小。有什么想法吗?
经过大量挖掘,发现问题出在 UIButton 与其标签之间的奇怪交互。有关该特定问题的更多详细信息,请参阅 this stack overflow post。虽然投票最多的解决方案都没有成功帮助我解决问题,但 a solution further down 确实有帮助。解决方案在于创建一个覆盖intrinsicContentSize 和layoutSubviews 的UIButton 子类。此类子类的代码在这里:
class LongTitleButton: UIButton {
override var intrinsicContentSize: CGSize {
return self.titleLabel?.intrinsicContentSize ?? super.intrinsicContentSize
}
override func layoutSubviews() {
super.layoutSubviews()
if let titleLabel = titleLabel {
titleLabel.preferredMaxLayoutWidth = titleLabel.frame.size.width
}
}
}
另外,由于这个问题似乎特定于 UIButton,因此同样有效的替代解决方案是简单地使用 UILabel 而不是 UIButton,而是在标签上放置一个 UIGestureRecognizer。
关于ios - 如何使用自动布局以动态高度居中 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46206302/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |