Get reference to NSLayoutConstraint using Identifier set in storyboard

Sam Shaikh picture Sam Shaikh · Oct 9, 2015 · Viewed 19.2k times · Source

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

Screenshot of constraint's properties

I want to make a reference to this constraint, to change its value in code, to move an object.

How can I get a reference to this NSLayoutContraint from this Identifier.

I read the documentation, it was written like this

@interface NSLayoutConstraint (NSIdentifier)
/* For ease in debugging, name a constraint by setting its identifier, which will be printed in the constraint's description.
 Identifiers starting with UI and NS are reserved by the system.
 */
@property (nullable, copy) NSString *identifier NS_AVAILABLE_IOS(7_0);

@end

So I realized that it's for debugging purposes.

What if I want to get it and use it? I saw this link, but no satisfactory answer was given: How to get NSLayoutConstraint's identifier by Its pointer?

Answer

Venk picture Venk · Nov 18, 2016

In Swift 3,

 let filteredConstraints = button.constraints.filter { $0.identifier == "identifier" }
 if let yourConstraint = filteredConstraints.first {
      // DO YOUR LOGIC HERE
 }