【问题标题】:how to add the touch area of a button?如何添加按钮的触摸区域?
【发布时间】:2016-06-22 11:43:47
【问题描述】:
selectgroup = [UIButton buttonWithType:UIButtonTypeCustom];
selectgroup.frame  = CGRectMake(screenWidth/4-23/2, 158, 23, 23) ;
selectgroup.hidden = NO;
UIImage *selectgroupimg = [UIImage imageNamed:@"groupicon2.png"];
[selectgroup setBackgroundImage:selectgroupimg forState:UIControlStateNormal];
//[selectgroup setcontentEdgeInsets : UIEdgeInsetsMake(0, 150, screenWidht/2, 30)];
[selectgroup addTarget:self action:@selector(selectgroup:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:selectgroup];

我想将按钮的可点击区域增加到(0,150,screenwidth/2,30)。 我尝试设置contentEdgeInsetsimageEdgeinsets,但都不起作用。

我该怎么做?

【问题讨论】:

  • 可点击区域是什么意思?您可以点击按钮上的任何位置,它将调用其操作。
  • 增加触控区域
  • 你想增加按钮的宽度吗?
  • 如果我增加按钮宽度,图像会出错
  • 在 UIImageView 中添加图像,然后添加背景清晰的按钮,使按钮尽可能大。

标签: ios uibutton


【解决方案1】:

你需要像设置图片一样(按钮属性setImage和setBackgroundImage都不一样)

UIImage *btnImage = [UIImage imageNamed:@"image.png"];
[buttonObject setImage:btnImage forState:UIControlStateNormal];forState:UIControlStateNormal];

然后设置你想要的按钮框架

buttonObject.frame  = CGRectMake(0,150,screenwidth/2,30);

【讨论】:

    【解决方案2】:

    子类 UIButton,或类别/扩展,并像这样使用它:

    -(BOOL) pointInside:(CGPoint)point withEvent:(UIEvent *)event {
        return CGRectContainsPoint(UIEdgeInsetsInsetRect(self.bounds, UIEdgeInsetsMake(-44, -44, -44, -44)), point);
    }
    

    【讨论】:

    • 什么是 self.bounds ?
    • @WaitakJong self = 你的按钮。您应该在 UIButton 的子类上添加此方法,此方法将覆盖 UIButton 功能。