2015-09-23 167 views
0

我想在UIImageView的右上角以編程方式製作一個UIButton,到目前爲止我有一個UIImageView,並且我想在UIImageView的右上角創建一個UIButton,圖像被加載到圖像視圖。我不知道我怎麼能做到這一點。在UIImageView的右上邊緣添加UIButton

UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; 
         [button setTitle:@"X" forState:UIControlStateNormal]; 
         [button sizeToFit]; 
         button.center = CGPointMake(self.img1.frame.origin.x+self.img1.frame.size.width,self.img1.bounds.origin.y); 

[self.img1 addsubView:button];

這裏,img1是圖像視圖。我想在img1的右上角添加該按鈕。

我該如何做到這一點?

+0

什麼是你的代碼的問題? –

+0

不確定@ Mr.T。它不會被添加到ImageView的右上角,這就是我想要實現的。 – Rosh

+0

調試調試視圖層次結構以查看按鈕的確切位置 –

回答

2
[self.img1 addSubView:button]; 
[button setFrame:CGRectMake(self.img1.size.width-button.frame.size.width,0,button.frame.size.width, button.frame.size.height)]; 
+0

謝謝@Idrees Ashraf。我不確定它爲什麼不起作用。我可能會錯過一些我無法弄清的東西。一旦我發現我會接受你的答案。 – Rosh

0

您也可以爲此使用自動佈局。

NSMutableArray * constraints = [NSMutableArray array]; 
[constraints addObject:[NSLayoutConstraint constraintWithItem:self.contentView 
    attribute:NSLayoutAttributeTopMargin 
    relatedBy:NSLayoutRelationEqual 
    toItem:separatorView 
    attribute:NSLayoutAttributeY 
    multiplier:1.0 
    constant:0]]; 
[constraints addObject:[NSLayoutConstraint constraintWithItem:self.contentView 
    attribute:NSLayoutAttributeRightMargin 
    relatedBy:NSLayoutRelationEqual 
    toItem:separatorView 
    attribute:NSLayoutAttributeRight 
    multiplier:1.0 
    constant:0]]; 
[button addConstraints:constraints]; 
[self.img1 addsubView : button]; 
0
UIImageView *img1 = [[UIImageView alloc] initWithFrame:CGRectMake(imageX,imageY,imageWidth,imageHeight)]; 

float buttonWidth = 30; 

UIButton *button =[ [UIButton alloc] initWithFrame:CGRectMake(img1.frame.size.width - buttonWidth,0, buttonWidth,buttonHeight)]; 

[self.view addSubView:img1]; 

[img1 addSubView:button];