如何修改NSLayoutConstraint的multiplier

因为项目用了xib创建cell,里面的控件约束和cell的宽度有关,然而cell在xib的宽度是固定的,只有显示到屏幕之后才会调整,导致控件布局就不对了,为了实现控件能动态根据cell的宽度调整控件本身的宽度,决定动态修改NSLayoutConstraint的multiplier的值(不知道这个值什么意思的去查阅iOS autolayout公式)。但是multiplier是一个只读属性,查找一番之后,成功在stackoverflow找到答案,特意分享出来,给有需要的人。原网站在这里

swift 2.3版本:

import Foundation
import UIKit

extension NSLayoutConstraint {

func setMultiplier(multiplier:CGFloat) -> NSLayoutConstraint {

    NSLayoutConstraint.deactivateConstraints([self])

    let newConstraint = NSLayoutConstraint(
        item: firstItem,
        attribute: firstAttribute,
        relatedBy: relation,
        toItem: secondItem,
        attribute: secondAttribute,
        multiplier: multiplier,
        constant: constant)

    newConstraint.priority = priority
    newConstraint.shouldBeArchived = self.shouldBeArchived
    newConstraint.identifier = self.identifier

    NSLayoutConstraint.activateConstraints([newConstraint])
    return newConstraint
    }
}

swift 3.0版本

import Foundation
import UIKit
extension NSLayoutConstraint {
    /**
     Change multiplier constraint

     - parameter multiplier: CGFloat
     - returns: NSLayoutConstraint
    */
    func setMultiplier(multiplier:CGFloat) -> NSLayoutConstraint {

        NSLayoutConstraint.deactivate([self])

        let newConstraint = NSLayoutConstraint(
            item: firstItem,
            attribute: firstAttribute,
            relatedBy: relation,
            toItem: secondItem,
            attribute: secondAttribute,
            multiplier: multiplier,
            constant: constant)

        newConstraint.priority = priority
        newConstraint.shouldBeArchived = self.shouldBeArchived
        newConstraint.identifier = self.identifier

        NSLayoutConstraint.activate([newConstraint])
        return newConstraint
    }
}

你可能感兴趣的:(如何修改NSLayoutConstraint的multiplier)