【问题标题】:Adding UIButton on the top right edge of the UIImageView在 UIImageView 的右上角添加 UIButton
【发布时间】:2015-09-23 14:43:29
【问题描述】:

我正在尝试以编程方式在 UIImageView 的右上角创建一个 UIButton,到目前为止,我有一个 UIImageView,并且我想在图像加载到图像视图时在 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 : 按钮];

这里,img1 是一个图像视图。我想在 img1 的右上角添加那个按钮。

我怎样才能做到这一点?

【问题讨论】:

  • 您的代码有什么问题?
  • 不确定@Mr.T.它没有添加到 ImageView 的右上角,这就是我想要实现的。
  • 查看调试视图层次结构以查看按钮的确切位置

标签: ios objective-c uiimageview uibutton


【解决方案1】:
[self.img1 addSubView:button];
[button setFrame:CGRectMake(self.img1.size.width-button.frame.size.width,0,button.frame.size.width, button.frame.size.height)];

【讨论】:

  • 感谢@Idrees Ashraf。我不确定为什么它不起作用。我可能遗漏了一些我无法弄清楚的东西。一旦我弄清楚我会接受你的回答。
【解决方案2】:

您也可以为此使用自动布局。

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

【讨论】:

    【解决方案3】:
    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];
    

    【讨论】:

      猜你喜欢
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 2016-04-29
      • 2016-01-07
      • 1970-01-01
      • 2020-08-27
      • 2015-11-02
      相关资源
      最近更新 更多