Adding an extra screen screen

I am trying to add a small icon in the center of the iPhone screen. Below is the code that I think should work, but it does not center it. The position relative to the width is fine, but the height is 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? Perhaps placing it according to the entire size of the application window, rather than this kind of screen?

+6
source share
3 answers

This should be self.view.frame.size.height/2 - 18 . An easier way is to simply install it as follows:

 pinMarkerView.center = self.view.center; 

But without knowing what a parental view is, it is impossible to say how to bring the image to the center of the screen.

+13
source

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]; 
+4
source

Here is the solution

Instead of self.view.frame.size.width

Use :: [UIScreen mainScreen] .bounds.size.width or height

So the code

 UIImage *pinMarker = [UIImage imageNamed:@"red_pen_marker.png"]; UIImageView *pinMarkerView = [[UIImageView alloc] initWithImage:pinMarker]; pinMarkerView.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 2, [UIScreen mainScreen].bounds.size.height / 2 , 18, 36); [self.view addSubview:pinMarkerView]; 
+3
source

Source: https://habr.com/ru/post/945897/


All Articles