Creating object programmatically and changing that

2019-07-21 12:27发布

I am trying to create a couple of UIImageViews (preferably with a for loop) and then afterwards move them, but I don't know how because I'm having trouble figuring out how to reference them if they will be made programmatically.

So I want something like this:

    for (int i = 0; i < 2; i++)
    {
        UIImageView *iv = [[UIImageView alloc]initWithImage:[UIImage imageNamed: picturo]];
        CGRect rect = CGRectMake((i * 50) + 50,30, 25, 25);
        [iv setFrame:rect];
        iv.tag = i;
        [self.view addSubview:iv];
    }

    (iv with tag of 0).center.y = 80; // <-- How do I do that!!

Obviously this example has no practical use and I could just change y value of 'rect' above to 80, but I want to know how to:

a. Create multiple uiimageviews (or any object for that matter) and be able to identify/reference/manipulate each one individually (I don't know how but I would assume by either naming them uniquely or using tags) and

b. Be able to identify/reference/manipulate an object that was created programmatically.

1条回答
ら.Afraid
2楼-- · 2019-07-21 13:05

creating views with tags works the way you have it.

To access those views use the viewWithTag property on a view to identify one of it's subviews:

  UIView* subview = [self.view viewWithTag:0];
  subview.center = CGPointMake(subview.center.x, 80);

(you cannot write to a view.center's x or y, you have to recreate the whole thing. Likewise with other geometric structs such as CGSize, CGRect)

查看更多
登录 后发表回答