문제

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