Swift NSLayoutConstraint 加约束Constraint

寇开畅
2023-12-01

//与父视图的左右间距10//NSLayoutFormatDirectionLeadingToTrailing

//水平方向上goodPicImage距离父控件左边10个像素距离,距离右边10个像素 H: 代表水平方向 V:代表垂直方向  |:代表距离父控件 [name]:标示控件名

        NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[goodPicImage]-10-|", options:NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views:["goodPicImage":goodPicImage]))

        NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[goodLabel]-10-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: ["goodLabel":goodLabel]))

        NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[goodDetailLabel]-10-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: ["goodDetailLabel":goodDetailLabel]))

        

        //上面与namelabel间距0 和下面goodLabel的间距是0

        let VConstaint = NSLayoutConstraint.constraintsWithVisualFormat("V:|-15-[goodPicImage(155)]-0-[goodLabel(15)]-0-[goodDetailLabel(15)]-0-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: ConstraintDictionWithArray([goodDetailLabel,goodLabel,goodPicImage], object: self))

        NSLayoutConstraint.activateConstraints(VConstaint)

// 因为swift 没有宏  所以 这个宏没有 NSDictionaryOfVariableBindings(...)  因此用下面的这个方法代替

/**

 * @param nameArray  你的子控件数组

 * @param object 父控件本身

 * 例子: ConstraintDictionWithArray([goodDetailLabel,goodLabel,goodPicImage],object: self) -->  ["goodDetailLabel":goodDetailLabel,"goodLabel":goodLabel,"goodPicImage":goodPicImage]

 */

func ConstraintDictionWithArray(nameArray:Array<UIView>,object:AnyObject) -> Dictionary<String,AnyObject> {
    
    var dict:Dictionary<String,AnyObject> = [:]
    
    var count:UInt32 = 0
    
    let ivars = class_copyIvarList(object.classForCoder, &count)
    
    for i in 0...Int(count) {
        
        let obj = object_getIvar(object, ivars[i])
        
        if let temp = obj as? UIView {
            
            if nameArray.contains(temp){
            
                let name = String.fromCString(ivar_getName(ivars[i]))!
                
                dict[name] = temp
            }
            
        }
    }
    free(ivars)
    
    return dict
}
 类似资料: