简体   繁体   English

设置UIButton的框架,但保持图像大小相同

[英]Set frame of UIButton but keep image same size

I have a UIButton in my app, and it's pretty small. 我的应用程序中有一个UIButton,它很小。 It can be quite hard to tap it sometimes. 有时很难敲打它。 Is there a way to have a 20px margin around the button, keeping the image the same size? 有没有办法在按钮周围留出20px的边距,以使图像大小相同? Here's my code: 这是我的代码:

self.helpButton= [UIButton buttonWithType:UIButtonTypeCustom];
[self.helpButton setImage:[UIImage imageNamed:@"Info Button.png"] forState:UIControlStateNormal];
[self.helpButton addTarget:self
           action:@selector(showHelp)
 forControlEvents:UIControlEventTouchUpInside];

if ([[ UIScreen mainScreen ] bounds ].size.height == 568 ) {
    self.helpButton.frame = CGRectMake(280.0, 528.0, 20, 20);
} else {
    self.helpButton.frame = CGRectMake(280.0, 440.0, 20, 20);
}

Basically, I want to have a larger area to tap, but keep the button the same size. 基本上,我希望有一个较大的区域可以点击,但要保持按钮的大小相同。

try with setImageEdgeInsets. 尝试使用setImageEdgeInsets。 check this. 检查一下。

  if ([[ UIScreen mainScreen ] bounds ].size.height == 568 ) {
         self.helpButton.frame = CGRectMake(280.0, 528.0, 40, 40);
  } else {
         self.helpButton.frame = CGRectMake(280.0, 440.0, 40, 40);
  }

  [self.helpButton setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];

子类化UIButton并重写backgroundRectForBounds:contentRectForBounds:或适用于您的用例的任何方法)。

If your button background colour is clear you can just increase the size of the button. 如果按钮背景色是透明的,则可以增加按钮的大小。 I did this for a delete button with a small image recently: 我最近对带有小图片的删除按钮做了此操作:

    UIImage *deleteImage = [UIImage imageNamed:@"btnDelete"];

    CGSize btnSize = CGSizeMake(deleteImage.size.width*2, deleteImage.size.height*2);

    self.deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];

    [_deleteButton setImage:deleteImage forState:UIControlStateNormal];

    _deleteButton.frame = CGRectMake(0,0,btnSize.width,btnSize.height);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM