我經常看到在UIViewController
中添加了自動佈局約束,但對於我來說這似乎是佈局邏輯的錯誤位置。在自定義UIView中添加自動佈局約束代碼的位置
是否可以在自定義UIView中添加NSLayoutConstraint
?
在一個UIView中,哪裏可以通過編程方式添加它們?
我經常看到在UIViewController
中添加了自動佈局約束,但對於我來說這似乎是佈局邏輯的錯誤位置。在自定義UIView中添加自動佈局約束代碼的位置
是否可以在自定義UIView中添加NSLayoutConstraint
?
在一個UIView中,哪裏可以通過編程方式添加它們?
我喜歡在視圖中設置自己的AutoLayout代碼,當它更有意義。我還發現,將customView中的所有約束設置爲init的一部分會更容易。
import UIKit
class customView:UIView
{
var customLabel:UILabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI()
{
// Setup UI
self.customLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(customLabel)
// Setup Constraints
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[customLabel]|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["customLabel":self.customLabel]))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[customLabel]-10-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["customLabel":self.customLabel]))
}
}
是否可以自定義的UIView中添加NSLayoutConstraints?
是的,可以在自定義視圖中添加約束條件,組織在這裏非常重要,尤其是如果您要爲自定義視圖的某些部分設置動畫效果時。
從蘋果公司的UIView Reference document
約束閱讀子類部分:
requiresConstraintBasedLayout - 如果你 視圖類需要限制正常工作實現此類方法。
updateConstraints - 如果您的視圖需要在子視圖之間創建 自定義約束,請實施此方法。
alignmentRectForFrame :, frameForAlignmentRect: - 實現這些 方法來覆蓋視圖如何與其他視圖對齊。
哪裏在UIView是正確的地方以編程方式添加它們?
這是一個自定義類的骨架大綱。關鍵的問題是你集中了你的約束條件,否則這個類會變得非常混亂,你添加的約束越多。您也可以在updateConstraints()方法中引入其他設置,並通過設置您的配置值來有條件地添加或移除約束,然後調用setNeedsUpdateConstraints()。
您決定要製作動畫的任何限制都應該是實例變量。
希望這有助於:)
class MyCustomView: UIView {
private var didSetupConstraints = false
private let myLabel = UILabel(frame: CGRectZero)
// MARK: Lifecycle
override init(frame: CGRect) {
super.init(frame: CGRectZero)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
// Mark: - Setup
private func setup() {
// 1. Setup the properties of the view it's self
self.translatesAutoresizingMaskIntoConstraints = false
backgroundColor = UIColor.orangeColor()
clipsToBounds = true
// 2. Setup your subviews
setupMyLabel()
// 3. Inform the contraints engine to update the constraints
self.setNeedsUpdateConstraints()
}
private func setupMyLabel() {
myLabel.translatesAutoresizingMaskIntoConstraints = false
}
override func updateConstraints() {
super.updateConstraints()
if didSetupConstraints == false {
addConstraintsForMyLabel()
}
}
private func addConstraintsForMyLabel() {
// Add your constraints here
}
}
@Tulleb我相信你忘了,如果限制在'updateConstraints)設置('設置'didSetupConstraints'到TRUE;。 –
請問@fragilecat? – Tulleb
@fragilecat如果在'updateConstraints()'中設置了約束,我相信你忘了將'didSetupConstraints'設置爲'true'。 –