在iOS应用中,我遇到了自动布局问题。
以下2个屏幕截图显示了该问题。
右侧的开关(UISwitch对象)应固定在水平位置。谁能看到发生了什么事?
的确,左边的字符串正在改变长度,但是我认为(根据我设置约束的方式)应重新设置字体大小或将字符串分成两行;但开关不会移位。
这是相关的快速代码:
import UIKit
class My_ViewController: UIViewController {
let xPanel = UILabel(), yPanel = UILabel(),
khToggle = UISwitch(), khLabel = UILabel()
....
override func viewDidLoad() {
super.viewDidLoad()
layOutUI()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
.....
toggleKeepHide(khToggle)
}
func layOutUI() {
for component in [xPanel,yPanel,khLabel,khToggle] {
component.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(component)
}
...........
khLabel.numberOfLines = 0
khLabel.adjustsFontSizeToFitWidth = true
khToggle.addTarget(self,
action: #selector(toggleKeepHide(_:)),
for: .valueChanged)
view.addConstraints([
.........
NSLayoutConstraint(item: khToggle, attribute: .right, relatedBy: .equal,
toItem: view, attribute: .right, multiplier: 1.0, constant: -30.0),
NSLayoutConstraint(item: khToggle, attribute: .top, relatedBy: .equal,
toItem: yPanel, attribute: .bottom, multiplier: 1.0,
constant: 50.0),
NSLayoutConstraint(item: khLabel, attribute: .right, relatedBy: .equal,
toItem: khToggle, attribute: .left, multiplier: 1.0, constant: -23.0),
NSLayoutConstraint(item: khLabel, attribute: .centerY, relatedBy: .equal,
toItem: khToggle, attribute: .centerY, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: khLabel, attribute: .left, relatedBy: .equal,
toItem: view, attribute: .left, multiplier: 1.0, constant: 30.0)])
}
@objc func toggleKeepHide(_ sender: UISwitch) {
if sender.isOn {khLabel.text = "Hide this object from the wyxoug list."}
else {khLabel.text = "Keep this object in the wyxoug list."}
}
}
使用setContentCompressionResistancePriority可以完成这项工作。但是我不太明白为什么宽度不明确(我不固定任何宽度),在UISwitch的右边是固定的,因为它必须是固定的对象,所以我假设其水平位置是完全确定的。
您要告诉AutoLayout将布局固定到相对于对象和父视图的确切值。但是,它无法根据属性的固有宽度来解析这些精确值。通过为其中一项提供较低的抗压强度,您正在告诉AutoLayout可以减小其中一项的宽度,从而允许其解析布局。
好的我明白了。在我看来,这是隐含的,因为AutoLayout可以自由压缩或折叠标签。这是我的错 虽然似乎有时以这种方式工作。
别担心,不仅是您。这是一组困难的API,尤其是带有多行标签的API。希望在几年后的某一天,SwiftUI将使其中的一些问题成为过去。