Get reference to NSLayoutConstraint using Identifier set in storyboard

前端 未结 6 1513
旧时难觅i
旧时难觅i 2020-12-30 02:02

I was setting the constraints of a button using a storyboard. I saw an option, \"Identifier\" in the constraint\'s properties.

6条回答
  •  Happy的楠姐
    2020-12-30 02:39

    I simplified the search and added in walking up the ancestor list of superviews:

    + (NSLayoutConstraint *) findConstraintNamed:(NSString *)identifierTarget startWith:(UIView *)aView;    
    {    
        // walk upward from item through ancestors  
        UIView *currentView = aView;            
    
        while (currentView != nil)    
        {    
            NSArray *constraints = [currentView constraints];    
            NSInteger foundConstraintIndex = [constraints indexOfObjectPassingTest:^BOOL(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {   
                return [((NSLayoutConstraint *)obj).identifier isEqualToString:identifierTarget];    
            }];
    
    
            if (foundConstraintIndex != NSNotFound)    
            {    
                return constraints[foundConstraintIndex];    
            }                
    
            // not found, so walk up the ancestor chain    
            currentView = currentView.superview;    
        }    
    
        return nil;  // not found anywhere in item or ancestors!  :(    
    }
    

提交回复
热议问题