【发布时间】:2018-02-07 04:52:21
【问题描述】:
我在 swift 中以编程方式创建了一个 UITextView,这就是我在 viewDidLoad() 中为我的控制器所拥有的。
let isPortrait = UIInterfaceOrientationIsPortrait(UIApplication.shared.statusBarOrientation)
if isPortrait {
searchTextView.widthAnchor.constraint(equalToConstant: view.frame.width * 0.7).isActive = true
} else {
searchTextView.widthAnchor.constraint(equalToConstant: view.frame.width * 0.1).isActive = true
}
这就是 searchTextView 的设置方式
func setupView() {
self.layer.cornerRadius = 8.0
self.translatesAutoresizingMaskIntoConstraints = false
self.textContainerInset = UIEdgeInsets(top: 12, left: 10, bottom: 0, right: 10)
self.textContainer.maximumNumberOfLines = 1
self.textContainer.lineBreakMode = .byTruncatingHead
self.autocorrectionType = .no
self.text = ""
self.font = Constants.fonts().largeFont
self.backgroundColor = UIColor.white
self.adjustsFontForContentSizeCategory = true
self.textColor = UIColor.black
self.layer.borderColor = UIColor.gray.cgColor
self.layer.borderWidth = 0.25
// Need clipsToBounds = false to show shadow
self.clipsToBounds = false
self.layer.shadowRadius = 20.0
self.layer.shadowColor = UIColor.gray.cgColor
self.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
self.layer.shadowOpacity = 0.5
self.tintColor = Constants.colors().primaryLightColor
}
这会根据设备方向为 searchTextView 提供不同的 widthAnchor。这很好用,但是,稍后我会检查设备方向何时会更改并删除并添加相应的 widthAnchors。
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
sideMenuLauncher.dismissSideMenu(duration: 0)
let toPortraitMode = self.view.frame.size.width > size.width
searchTextView.widthAnchor.constraint(equalToConstant: view.frame.width * 0.7).isActive = toPortraitMode
searchTextView.widthAnchor.constraint(equalToConstant: size.width * 0.1).isActive = !toPortraitMode
for constraint in view.constraints {
print("\(constraint)\n")
}
searchTextView.updateConstraints()
searchTextView.layoutIfNeeded()
}
但这实际上并没有停用任何约束,正如它在此控制台输出中所说:
(
"<NSLayoutConstraint:0x60c000896170 PickupApp.SearchBarView:0x7f7ee1016a00.width == 56.8 (active)>",
"<NSLayoutConstraint:0x604000c9c6b0 PickupApp.SearchBarView:0x7f7ee1016a00.width == 397.6 (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x604000c9c6b0 PickupApp.SearchBarView:0x7f7ee1016a00.width == 397.6 (active)>
我不明白为什么即使添加了约束也没有停用这些约束。
【问题讨论】:
-
@HarshalValanda 我相信该帖子是使用
@IBOutlets回答的,这需要使用情节提要,但我不使用情节提要。