美文网首页已解决
代码修改XIB约束比例multiplier属性

代码修改XIB约束比例multiplier属性

作者: 梦里桃花舞倾城 | 来源:发表于2018-10-25 09:22 被阅读39次

    multiplier属性是只读的,不可以进行直接修改。stackoverflow给出答案,特意分享出来,给有需要的人。原网站在这里

    OC写法

    - (void)p_changeMultiplierOfConstraint:(NSLayoutConstraint *)constraint multiplier:(CGFloat)multiplier {
        
        [NSLayoutConstraint deactivateConstraints:@[constraint]];
        NSLayoutConstraint *newConstraint = [NSLayoutConstraint constraintWithItem:constraint.firstItem attribute:constraint.firstAttribute relatedBy:constraint.relation toItem:constraint.secondItem attribute:constraint.secondAttribute multiplier:multiplier constant:constraint.constant];
        newConstraint.priority = constraint.priority;
        newConstraint.shouldBeArchived = constraint.shouldBeArchived;
        newConstraint.identifier = constraint.identifier;
        [NSLayoutConstraint activateConstraints:@[newConstraint]];
    }
    

    调用

            [self p_changeMultiplierOfConstraint:_proImgWidthCtt multiplier:0.5];
    

    Swift写法

    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
        }
    }
    

    原文链接

    相关文章

      网友评论

        本文标题:代码修改XIB约束比例multiplier属性

        本文链接:https://www.haomeiwen.com/subject/ssqqtqtx.html