先前答案的小扩展,因为 addConstraint 将来会被弃用。这是 UI 视图的扩展。在将视图添加到层次结构后使用这些函数。
OBJC
@implementation UIView (Constraints)
-(void)addConstaintsToSuperviewWithLeftOffset:(CGFloat)leftOffset topOffset:(CGFloat)topOffset {
self.translatesAutoresizingMaskIntoConstraints = false;
[[NSLayoutConstraint constraintWithItem: self
attribute: NSLayoutAttributeLeading
relatedBy: NSLayoutRelationEqual
toItem: self.superview
attribute: NSLayoutAttributeLeading
multiplier: 1
constant: leftOffset] setActive:true];
[[NSLayoutConstraint constraintWithItem: self
attribute: NSLayoutAttributeTop
relatedBy: NSLayoutRelationEqual
toItem: self.superview
attribute: NSLayoutAttributeTop
multiplier: 1
constant: topOffset] setActive:true];
}
-(void)addConstaintsWithWidth:(CGFloat)width height:(CGFloat)height {
self.translatesAutoresizingMaskIntoConstraints = false;
[[NSLayoutConstraint constraintWithItem: self
attribute: NSLayoutAttributeWidth
relatedBy: NSLayoutRelationEqual
toItem: nil
attribute: NSLayoutAttributeNotAnAttribute
multiplier: 1
constant: width] setActive:true];
[[NSLayoutConstraint constraintWithItem: self
attribute: NSLayoutAttributeHeight
relatedBy: NSLayoutRelationEqual
toItem: nil
attribute: NSLayoutAttributeNotAnAttribute
multiplier: 1
constant: height] setActive:true];
}
@end
斯威夫特 3
extension UIView {
public func addConstaintsToSuperview(leftOffset: CGFloat, topOffset: CGFloat) {
self.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: self,
attribute: .leading,
relatedBy: .equal,
toItem: self.superview,
attribute: .leading,
multiplier: 1,
constant: leftOffset).isActive = true
NSLayoutConstraint(item: self,
attribute: .top,
relatedBy: .equal,
toItem: self.superview,
attribute: .top,
multiplier: 1,
constant: topOffset).isActive = true
}
public func addConstaints(height: CGFloat, width: CGFloat) {
self.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: self,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: height).isActive = true
NSLayoutConstraint(item: self,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: width).isActive = true
}
}