I am trying to add a small icon in the center of my iPhone app screen. Below is the code I think should work, but it isn't centering it. The position regarding the width is fine, but the height is way off, about 100 pixels off?
UIImage *pinMarker = [UIImage imageNamed:@"red_pen_marker.png"];
UIImageView *pinMarkerView = [[UIImageView alloc] initWithImage:pinMarker];
pinMarkerView.frame = CGRectMake(self.view.frame.size.width/2 - 9, self.view.frame.size.height/2 - 36, 18, 36);
[self.view addSubview:pinMarkerView];
Any suggestions? Maybe placing it according to the entire app window size instead of this screens view?
It should be self.view.frame.size.height/2 - 18
. A simpler way is to just set it like this:
pinMarkerView.center = self.view.center;
But without knowing what the parent view is it is impossible to tell how to bring the imageView to the center of the screen.
I think NSLayoutConstraint should solve your problem
UIView *superview = self.view;
UIImage *pinMarker = [UIImage imageNamed:@"red_pen_marker.png"];
UIImageView *pinMarkerView = [[UIImageView alloc] initWithImage:pinMarker];
pinMarkerView.frame = CGRectMake(self.view.frame.size.width/2 - 9, self.view.frame.size.height/2 - 36, 18, 36);
[pinMarkerView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:pinMarkerView];
NSLayoutConstraint *myConstraint =[NSLayoutConstraint
constraintWithItem:pinMarkerView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0];
NSLayoutConstraint *myConstraint2 =[NSLayoutConstraint
constraintWithItem:pinMarkerView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0];
[superview addConstraint:myConstraint];
[superview addConstraint:myConstraint2];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With