0

I am working on an older iOS project, written mostly in Objective C. I have these line in the code (to set an object to the middle of the screen):

self.leftSpacingConstraint.constant = 250.0;
self.rightSpacingConstraint.constant = 250.0;

I would like to change these constraints relative to screen width. How would I do that? Thanks

Gefilte Fish
  • 1,600
  • 1
  • 18
  • 17

2 Answers2

1

Maybe like this:

[NSLayoutConstraint constraintWithItem:self
                         attribute:NSLayoutAttributeCenterX
                         relatedBy:NSLayoutRelationEqual
                            toItem:self.superview
                         attribute:NSLayoutAttributeCenterX
                        multiplier:1.f constant:0.f]];

Or, if you used .xib file, delete left and right constraints and add centerHorizontal

Kamil Harasimowicz
  • 4,684
  • 5
  • 32
  • 58
1

Take a look on the device's screen width, and apply the right constant depending on what you would like.

    // iPhone 6Plus / 6s Plust / 7Plus = 414
    // iPhone 6 / 6s / 7 / 7s = 375
    // iPhone 5 / 5s / SE = 325
    // sizes: http://www.idev101.com/code/User_Interface/sizes.html
    NSInteger screenWidth = (NSInteger)[[UIScreen mainScreen] bounds].size.width;
    CGFloat leftConstant = 0;
    CGFloat rightConstant = 0;
    switch (screenWidth) {
    case 325:
            leftConstant = 1;
            rightConstant = 1;
            break;
    case 375:
            leftConstant = 2;
            rightConstant = 2;
            break;
    case 414:
            leftConstant = 3;
            rightConstant = 3;
            break;
    }

    self.leftSpacingConstraint.constant = leftConstant;
    self.rightSpacingConstraint.constant = rightConstant;

This is a simple approach, you can define macros for example, or pull third party libraries into our project.

dirtydanee
  • 6,081
  • 2
  • 27
  • 43