6

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?

4

3 回答 3

14

应该是self.view.frame.size.height/2 - 18。一种更简单的方法是像这样设置它:

pinMarkerView.center = self.view.center;

但是如果不知道父视图是什么,就不可能知道如何将 imageView 带到屏幕的中心。

于 2013-05-26T23:35:25.560 回答
4

我认为 NSLayoutConstraint 应该可以解决您的问题

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];
于 2013-05-27T07:12:10.857 回答
3

这是一个解决方案

而不是 self.view.frame.size.width

使用:: [UIScreen mainScreen].bounds.size.width or height

所以代码是

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];
于 2014-11-12T06:32:26.653 回答