[英]Need help properly positioning UIView in a UIView
我制作了一个UIView子类(碗),当我尝试在碗内制作一个碗然后将内部碗放在外面的中心时,它最终被放置在中心的下方和右侧。 我如何正确地居中呢?
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
//CGColorRef lightGrayColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0 blue:230.0/255.0 alpha:1.0].CGColor;
self.userInteractionEnabled = YES;
UIGestureRecognizer *twoFingerZ = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchZoom:)] ;
[self addGestureRecognizer:twoFingerZ];
UILabel *label = [[UILabel alloc] init];
[label setFont:[UIFont fontWithName:@"Arial" size:64]];
label.text = [NSString stringWithFormat:@"March"];
[label sizeToFit];
label.center = self.center;
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor lightGrayColor];
self.backgroundColor = [UIColor whiteColor];
[self addSubview:label];
}
return self;
}
-(void)pinchZoom:(UIPinchGestureRecognizer *)recognizer
{
if([(UIPinchGestureRecognizer*)recognizer state] == UIGestureRecognizerStateEnded) {
CGAffineTransform newForm = CGAffineTransformMakeScale(600/self.bounds.size.width, 600/self.bounds.size.height);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
[self setTransform:newForm];
return;
[UIView commitAnimations];
}
if([(UIPinchGestureRecognizer*)recognizer state] == UIGestureRecognizerStateBegan) {
subClip = [[clipView alloc] initWithFrame:CGRectMake((self.center.x - ([delegate getSize:self].width/2)), (self.center.y - ([delegate getSize:self].height/2)), [delegate getSize:self].width, [delegate getSize:self].height)];
subClip.transform = CGAffineTransformMakeScale(0.1, 0.1);
[self addSubview:subClip];
bowl *newB = [[bowl alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];
newB.center = self.center;
// right here! *************
[self addSubview:newB];
}
recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
recognizer.scale = 1;
}
编辑:我修好了。 显然UIView的中心值并不是我想象的那样(看起来它是中心在另一个视图中的位置或其他东西),所以不是newB.center = self.center,正确的方法来做到这一点是newB.center = CGPointMake(self.frame.size.width / 2,self.frame.size.height / 2);
要使内部标签居中,您应该能够使用:
label.center=CGPointMake(self.center.x,self.center.y);
但首先你可能想要定义内部标签的框架大小:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,yourWidth,yourHeight);
您可能还希望将文本居中在内部标签中:
label.textAlignment = UITextAlignmentCenter;
此外,不确定您在代码中的意图:
[label sizeToFit];
但根据文档 ,sizeToFit将调整大小并移动接收器视图,以便它包含其子视图。 在这种情况下,您的内部视图似乎没有子视图。 因此,您的居中可能会关闭,因为您的内部标签可能有意想不到的尺寸。 尝试将该标签的背景颜色设置为您可以看到的内容(即不是[UIColor clearColor]
)以仔细检查其尺寸。 可能有助于解决定心问题。
祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.