Rosh
Rosh

Reputation: 169

Adding UIButton on the top right edge of the UIImageView

I am trying to make a UIButton programatically on top right corner of UIImageView, so far I have an UIImageView and I want to create a UIButton on top right edge of the UIImageView whenever the image is loaded to the image view. I am not sure how could I achieve that.

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

Here , img1 is an image view. I want to add that button on top right of the img1.

How can I achieve that?

Upvotes: 0

Views: 1664

Answers (3)

Hanushka Suren
Hanushka Suren

Reputation: 793

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

Upvotes: 0

piyuj
piyuj

Reputation: 163

You can also use autolayout for this.

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

Upvotes: 0

Idrees Ashraf
Idrees Ashraf

Reputation: 1383

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

Upvotes: 2

Related Questions