简体   繁体   English

UIViewAutoresizingFlexibleLeftMargin,参考iOS上的Superview

[英]UIViewAutoresizingFlexibleLeftMargin with Reference to Superview on iOS

I'm dynamically adding an error icon to fields in a form as shown here: 我正在动态地向表单中的字段添加错误图标,如下所示:

错误图标

I'm generating the icon in code, and I want to position it on the top-right of its superview, but I can't get it to go where I want it. 我在代码中生成了图标,我想将它放在超级视图的右上角 ,但我无法将它放在我想要的地方。 The screenshot shows how it stays on the left, but it should be on the right. 屏幕截图显示了它如何保持在左侧,但它应该在右侧。

Here's my code: 这是我的代码:

//Create the image
UIImageView *errorIcon =[[UIImageView alloc] initWithFrame:CGRectMake(-10,-10,23,23)];

//Set the image file
errorIcon.image = [UIImage imageNamed:@"error.png"];

//Tell the image to position it on the top-right (flexible left margin, flexible bottom margin)
errorIcon.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin;

No matter what I set the frame's x value to, I can't get it to stick on the right. 无论我将框架的x值设置为什么,我都无法将其固定在右侧。

What am I doing wrong with the frame and/or the autoResizingMask ? 我在frame和/或autoResizingMask做错了什么?

Autoresizing rules only kick in when you resize the view or superview, it's not for setting initial position. 只有在调整视图或超级视图大小时才会启用自动调整规则,而不是设置初始位置。 Plus your error icon origin (-10, -10) is just outside top left corner. 加上您的错误图标原点(-10, -10)就在左上角的外面。 What you probably need is just: 你可能需要的只是:

UIImageView *errorIcon = [[UIImageView alloc] initWithImage:errorImage];
errorIcon.center = CGPointMake(yourFieldView.frame.size.width, 0);
[yourFieldView addSubview:errorIcon];

Your problem is this line: 你的问题是这一行:

UIImageView *errorIcon = 
    [[UIImageView alloc] initWithFrame:CGRectMake(-10,-10,23,23)];

That means the top left of the superview. 这意味着超级视图的左上角。 If that isn't where you want to put it, don't put it there! 如果那不是你想放的地方,不要把它放在那里!

The top right is here: 右上角是这里:

UIImageView *errorIcon = 
    [[UIImageView alloc] initWithFrame:
        CGRectMake(superview.bounds.size.width-10,-10,23,23)];

(For superview substitute a reference to the view that will be the superview.) (对于superview替换对将成为superview的视图的引用。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM