Strong Like Bull
Strong Like Bull

Reputation: 11297

How to dynamically add a UIImageView to a view and position items?

I have an app where it reads an XML document containing 2 fields (image url and description). If the document has a field that has a valid image URL, I want the view to show the image. Else I just want it to show the description.

The problem I am having is :

  1. how to show the UIImageView dynamically
  2. how to move the UITextView downwards since now I added a UIImageView

Currently I just have a View with a UITextView on it.

Any ideas?

Upvotes: 2

Views: 2081

Answers (2)

Totumus Maximus
Totumus Maximus

Reputation: 7573

The following is what you could do.

Prepare the the view with the UIImageView and the UITextView in the viewDidLoad like this:

-(void) viewDidLoad)
{
    [super viewDidLoad];
    myImageView = [[UIImageView alloc] init];
    myImageView.frame = CGRectMake(x,y,0,0); //you can set it at the right position and even set either the width OR the height depending on where you want the textView in my example I'm gonna assume its beneath the imageView
    //other imageView settings
    [myView addSubView:myImageView];

    myTextView = [[myTextView alloc] init];
    myTextView.frame = CGRectMake(x,y,width,heigh+CGRectGetMaxY(myImageView.frame)); //here you prepare the textView for the imageView and the space it takes. But doesn't get hindered by it if it's not there.
    //other textView settings.
    [myView addSubView:myTextView];

    //You would want this loading function about here OR after this loading has been occured.
    [self loadImageFromURL];
}

-(void)loadImageFromURL
{
    //get your image here.. or not

    if(imageHasLoaded) //some condition that gets set when your image has successfully loaded. (This should be done in a delegate (didLoadImageFromURL) if you have such thing prepared.
    {
        //myImageView.image = theLoadedImage;
        myImageView.frame = CGRectMake(x,y,theLoadedImageWidth,theLoadedImageHeight);
        //after you set the frame of the imageView you need to refresh the view
        [myView setNeedsDisplay];
    }
}

And this is how you should dynamically add an imageView with image and frame to some view.

Upvotes: 1

justin
justin

Reputation: 104698

1) -[UIView setHidden:] if the UIImageView is already in place. Otherwise, [[UIImageView alloc] initWithFrame:], then add the image view as a subview to the view.

2) -[UIView setFrame:] (is one option)

Upvotes: 2

Related Questions