2013-12-11 38 views
0

我正在嘗試將圖像添加到我的視圖中。我嘗試下面的代碼:以編程方式創建UIImageView

UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tag40pixelsborder.png"]]; 
    imgView.frame = CGRectMake(200, 200, 30, 30); 
// imgView.bounds = CGRectMake(300, 300, 32, 32); 
    [imgView setContentMode:UIViewContentModeScaleAspectFit]; 
    [self.view addSubview:imgView]; 


    NSLog(@"frame x %f", imgView.frame.origin.x); 
    NSLog(@"frame y %f", imgView.frame.origin.y); 

但圖片不顯示在屏幕上,並返回的NSLog 30.00「x」和0.00「Y」如果我取消了邊界線和我刪除了框線「80」爲「x」,80.00爲「y」。

我使用autolayout,但完全相同的代碼在另一個視圖上工作!怎麼了?

+0

你的圖像的尺寸是多少? – slecorne

+0

該代碼適用於我,你添加圖像到xcode檢查圖像的拼寫 – Yohan

+0

我複製 - 粘貼圖像的名稱,我敢肯定它是好的。 – anthoprotic

回答

1

如果你想使用自動佈局來做到這一點,那麼你應該沿着這些線做些事情。

UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tag40pixelsborder.png"]]; 
imgView.translatesAutoresizingMaskIntoConstraints = NO; 
[imgView setContentMode:UIViewContentModeScaleAspectFit]; 
[imgView sizeToFit]; 
[self.view addSubview:imgView]; 

那麼你將要設置自動佈局限制什麼,我看你有沒有爲x = 200 Y = 200

NSArray *constraints = [NSLayoutConstraint 
         constraintsWithVisualFormat:@"V:|-(200)-[imgView]" 
         options:0 
         metrics:nil 
         views:@{ @"imgView" : imgView }]; 
[self.view addConstraints:constraints]; 

constraints = [NSLayoutConstraint 
       constraintsWithVisualFormat:@"|-(200)-[imgView]" 
       options:0 
       metrics:nil 
       views:@{ @"imgView" : imgView }]; 
[self.view addConstraints:constraints]; 

以上會使圖像視圖200從頂部和200在這種情況下,父視圖的左邊即self.view。

如果你想添加高度,你可以刪除[imgView sizeToFit],只需在高度和寬度上添加高度,即| - (200) - [imgView(width)]和相同的高度標有V :.

+0

我試過你的解決方案,但我得到「沒有已知的類選擇器'constraintsWithVisualFormat:options:metrics:views'」從Xcode的方法。我忘了導入一些東西嗎? – anthoprotic

+0

然而,圖像現在顯示出來(與您的前5行代碼),但它在原始分辨率(160x160),並且每當我想要更改幀/邊界,它會消失。 – anthoprotic

+0

您正在使用自動佈局並且iOS> = 6? – darren102

1

如果你使用autolayout就像你說的,你應該避免從代碼中添加子視圖!如果你想這樣做,你應該編程添加constrains也。你的代碼很好,但自動佈局卻搞不清楚。如果你想要骯髒的解決方案,你應該在加載所有東西后添加這個ImageView(例如在viewDidAppear:方法中)。

+0

感謝您的解決方案,但它沒有工作,即使在ViewDidAppear。我需要什麼樣的限制才能使其工作?我不認爲這是正常的,我得到這種NSLog – anthoprotic