我想在 Swift 中子类化 NSLayoutConstraint
以提供更简单的方法来实例化常见约束(例如 height
、width
...) .
到目前为止,我编写的代码草稿无法正常工作,因为无法写入 item
-properties:
class TestConstraint: NSLayoutConstraint {
init(item: Any) {
super.init()
self.firstItem = item // WARNING: Cannot assign to property: 'firstItem' is a get-only property
// ...
}
}
是否有可能以这种方式子类化 NSLayoutConstraint
还是我必须额外考虑其他因素?
最佳答案
我认为您需要的是 UIView 的扩展。
extension UIView{
func anchor(top:NSLayoutYAxisAnchor?,leading:NSLayoutXAxisAnchor?,trailing:NSLayoutXAxisAnchor?,bottom:NSLayoutYAxisAnchor?,padding:UIEdgeInsets = .zero,size:CGSize = .zero){
translatesAutoresizingMaskIntoConstraints = false
if let top = top{
topAnchor.constraint(equalTo: top, constant: padding.top).isActive = true
}
if let leading = leading{
leadingAnchor.constraint(equalTo: leading, constant: padding.left).isActive = true
}
if let trailing = trailing{
trailingAnchor.constraint(equalTo: trailing, constant: -padding.right).isActive = true
}
if let bottom = bottom{
bottomAnchor.constraint(equalTo: bottom, constant: -padding.bottom).isActive = true
}
if size.width != 0{
widthAnchor.constraint(equalToConstant: size.width).isActive = true
}
if size.height != 0{
heightAnchor.constraint(equalToConstant: size.height).isActive = true
}
}
}
关于swift - 在 Swift 中子类化 NSLayoutConstraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51577782/