Getting an existing NSLayoutConstraint for the width?

前端 未结 3 652
自闭症患者
自闭症患者 2021-02-02 14:40

I\'m trying to animate a control in Cocoa with auto layout.

Now, I can set [[constraint animator] setConstant:newWidth];, which works. But how can I get the

相关标签:
3条回答
  • 2021-02-02 14:45

    Every contraint has an attribute [constraint firstAttribute] It returns an enum NSLayoutAttribute

    typedef NS_ENUM(NSInteger, NSLayoutAttribute) {
        NSLayoutAttributeLeft = 1,
        NSLayoutAttributeRight,
        NSLayoutAttributeTop,
        NSLayoutAttributeBottom,
        NSLayoutAttributeLeading,
        NSLayoutAttributeTrailing,
        NSLayoutAttributeWidth,
        NSLayoutAttributeHeight,
        NSLayoutAttributeCenterX,
        NSLayoutAttributeCenterY,
        NSLayoutAttributeBaseline,
    
        NSLayoutAttributeNotAnAttribute = 0
    };
    

    so you can check NSLayoutAttributeWidth for width.

    Sample code:

    NSArray constraints = [self constraints];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstAttribute = %d", NSLayoutAttributeWidth];
    NSArray *filteredArray = [constraints filteredArrayUsingPredicate:predicate];
    if(filteredArray.count == 0){
          return nil;
    }
    NSLayoutConstraint *constraint =  [constraints objectAtIndex:0];
    
    0 讨论(0)
  • 2021-02-02 14:49

    I wrote a reusable extension: (Swift 4.1)

    /**
     * Utils when working with constraints
     */
    extension NSLayoutConstraint{
        /**
         * Returns all constraints of kinds
         * EXAMPLE: NSLayoutConstraint.ofKind(rect.immediateConstraints, kinds: [.width,.height]) //width, height
         */
        static func ofKind(_ constraints:[NSLayoutConstraint],kinds:[NSLayoutAttribute]) -> [NSLayoutConstraint]{
            return kinds.map { kind in
                return constraints.filter { constraint in
                    return constraint.firstAttribute == kind
                }
            }.flatMap({$0})//flattens 2d array to 1d array
        }
    }
    
    0 讨论(0)
  • 2021-02-02 15:10

    Here is the swift 3 version tested on Xcode 8.2.1 and macOS 10.12.2.

    The code shows how to get a button's width and height constraints, but you could filter whatever you want from NSLayoutAttribute enum.

    let cons = signInButton.constraints.filter {
        $0.firstAttribute == NSLayoutAttribute.width || $0.firstAttribute == NSLayoutAttribute.height /// or other from `NSLayoutAttribute`
    }
    // do something with the constraints array, e.g.
    NSLayoutConstraint.deactivate(cons)
    
    0 讨论(0)
提交回复
热议问题