Search code examples
objective-cautolayoutnslayoutconstraint

How to constraint the center of a UIButton object to its superview without Interface Builder


G'day, All! Excuse me for being a tad troublesome, but despite all my efforts, I have failed to get auto layout stuff to work in my code. I am building my iOS app without Xcode, mainly on the command line. As a result, I think it might cause some issues relevant to Auto Layout. Please find below the simplest attempt to constraint the center of a UIButton object to its superview.

So far I have had a go at various Layout techniques including Anchoring, NSLayotConstraint constraintWithItem: and VFL. None of the above has had any effect on the position of the subviews. I get neither compile nor runtime errors. TranslatesAutoresizingMaskIntoConstraints is OFF. Honestly, it beats me what makes my code not behave as expected. What's more, I have gone through numerous Auto Layout examples available online. Any help would be genuinely appreciated.

{
  NSLayoutConstraint    *constraint;

  [aButton setTranslatesAutoresizingMaskIntoConstraints:NO];
  constraint =
    [NSLayoutConstraint
      constraintWithItem:aButton
      attribute:NSLayoutAttributeCenterX
      relatedBy:NSLayoutRelationEqual
      toItem:aButton.superview
      attribute:NSLayoutAttributeCenterX
      multiplier:1.0f
      constant:0.0f];
  constraint.active = YES;
  [aButton.superview addConstraint:constraint];
  constraint =
    [NSLayoutConstraint
      constraintWithItem:aButton
      attribute:NSLayoutAttributeCenterY
      relatedBy:NSLayoutRelationEqual
      toItem:aButton.superview
      attribute:NSLayoutAttributeCenterY
      multiplier:1.0f
      constant:0.0f];
  constraint.active = YES;
  [aButton.superview addConstraint:constraint];
}```

Solution

  • As it turns out, the hitch was brought on by my linking the wrong SDK. Instead of iPhoneSimulator.sdk, I should have utilized iPhoneSimulator12.1.sdk.

    -isysroot $(ISYS_ROOT)
    ISYS_ROOT = /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk
    

    A million thanks to everyone who strove to help.