2010-07-23 72 views
16

如何在objective-c中创建和定位新的imageview?Cocoa Touch - 以编程方式添加UIImageView?

谢谢!

我试过,但它似乎没有做任何事情...

-(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]; 

我把这个方法在我的ViewController。我看到一些需要导入核心图形的CG东西吗? (无论如何,什么是核心图形?)

回答

60

您正在询问iPhone图像视图。对?然后尝试此

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

这将创建父视图的100×50尺寸和定位(10,10)的图像图。

检查参考手册UIImageViewUIView。您可以使用imageView的image属性来设置图像。

​​

你也可以使用的UIView的contentMode属性来配置如何在视图适合图像。例如,您可以使用

imgView.contentMode = UIViewContentModeCenter
将所需图像放置到视图的中心。可用内容模式列出 here

+0

如何定义要显示的图像? 是的,可可触摸只是iPhone。 – user377419 2010-07-23 20:52:25

+0

也是什么限制的位置..像什么最大值之前,它熄灭屏幕? – user377419 2010-07-23 20:59:35

+0

回答编辑。希望它对你有所帮助。 – taskinoor 2010-07-24 03:28:00

22

您尚未将视图作为子视图添加到另一个视图,这意味着它不在视图层次结构中。

假设你在一个视图控制器这样做,它可能看起来像:

[self.view addSubview: imgView]; 
+0

它的工作原理! ! – user377419 2010-07-24 13:28:39

+0

@Darryl,在视图控制器中水平添加图像,如果我想要然后垂直布局,该怎么办? – user2070775 2014-08-21 03:06:48

0

我有问题与值传递NSSArrayNSString

我得到了答案:

//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.. 
1
(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]; 
} 
相关问题