Search code examples
objective-ciossubviewsuperviewuiview-hierarchy

How to Insert View in Superview's View? (iOS)


I have the line of code below... How would I modify it to insert the subview in the superview's view named 'foo'?

[[self superview] addSubview:copy3];

Solution

  • There are more than 1 ways of doing this -

    1.have an IBOutlet reference in your code. This is created from xcode Interface builder. Once you have this then it fairly straight forward -

    [iboutlet_foo_object addSubview:copy3];
    

    2.tag the view that you are interested in. Again tagging a view can be done from xcode Interface builder or from code. After that -

    Foo *fooObj = [[self superview] viewWithTag:tagInt];
    [fooObj addSubview:copy3];
    

    3.Finally you can iterate through all the views in your superview & see which one is of type Foo -

    NSArray *subviews = [[self superview] subviews];
    for(UIView *v in subviews)
    {
        if(v isKindOfClass:[Foo class])
        {
            [v addSubview:copy3];
            break;
        }
    }
    

    hope these methods help you...