Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding subview center of screen

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?

like image 680
jdog Avatar asked May 26 '13 23:05

jdog


2 Answers

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.

like image 167
Kedar Avatar answered Nov 09 '22 17:11

Kedar


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];
like image 20
Prashant Nikam Avatar answered Nov 09 '22 19:11

Prashant Nikam