質問

I'm dynamically adding an error icon to fields in a form as shown here:

error icon

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.

What am I doing wrong with the frame and/or the autoResizingMask?

役に立ちましたか?

解決

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.)

他のヒント

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. What you probably need is just:

UIImageView *errorIcon = [[UIImageView alloc] initWithImage:errorImage];
errorIcon.center = CGPointMake(yourFieldView.frame.size.width, 0);
[yourFieldView addSubview:errorIcon];
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top