Question

How can I create and position a new imageview in objective-c?

Thanks!

I tried this but it doesnt seem to do anything...

-(void)drawStars{ //uses random numbers to display a star on screen
    //create random position
    int xCoordinate = arc4random() % 10;
    int yCoordinate = arc4random() % 10;

    UIImageView *starImgView = [[UIImageView alloc] initWithFrame:CGRectMake(xCoordinate, yCoordinate, 58, 40)]; //create ImageView 

    starImgView.image = [UIImage imageNamed:@"star.png"];


    [starImgView release];

I placed this method in my viewcontroller. I see some CG stuff do I need to import core graphics or something? (what is core graphics anyway?)

Was it helpful?

Solution

You are asking about iPhone image view. Right? Then try this

UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 50)];

This will create an image view of 100 x 50 dimension and locating (10, 10) of parent view.

Check the reference manual for UIImageView and UIView. You can set an image by using image property of imageView.

imgView.image = [UIImage imageNamed:@"a_image.png"];

And you can use the contentMode property of UIView to configure how to fit the image in the view. For example you can use

imgView.contentMode = UIViewContentModeCenter
to place the desired image to the center of the view. The available contentModes are listed here

OTHER TIPS

You haven't added your view as a subview to another view, meaning it isn't in the view hierarchy.

Assuming you are doing this in a view controller, it might look something like:

[self.view addSubview: imgView];
(void)viewDidLoad {
   [super viewDidLoad];
   UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.layer.frame.size.width, self.view.layer.frame.size.height)];
   imgView.image = [UIImage imageNamed:@"emptyCart.jpeg"];
   imgView.backgroundColor = [UIColor whiteColor];
   imgView.contentMode = UIViewContentModeCenter;
   [self.view addSubview: imgView];
}

I had problem with passing the value NSSArray to NSString,

I got the answer:

//Display all images....
    NSString *imgstring= [self.allimages objectAtIndex:indexPath.row];
    cell.myimages.image=[UIImage imageNamed:imgstring];     //displaying Images in UIImageView..noproblem.

// Display all numbers...
    cell.mylables.text=[NSString stringWithFormat:@"%@", [mysetobjectAtIndex:indexPath.row ]];  //showing results fine ArghyA..
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top