2014-10-06 61 views
6

我正在尝试增加我的UIButton命中区域。我有一个新的Xcode项目,在故事板的中心有一个UIButton。该按钮通过插座和动作连接到我的视图控制器。我以编程方式能够更改按钮标题,只是为了获得乐趣,因为当我点击按钮时,操作会改变视图的背景。所以我知道一切都连接起来并且有效。xcode iOS增加UIButton命中区域

从我在线阅读,这应该工作,但它不是。

[button setFrame:CGRectMake(button.frame.origin.x,button.frame.origin.y,-64,-64)];

有什么想法?我尝试过没有负边距,也没有效果。顺便说一句,我已经尝试了这个问题的许多地方被问到,但它不工作。感谢您的帮助。另外,我听说UIButton的子类化会产生一个问题,对此有何看法?

更新: 我想要做的UIButton有一个背景颜色,是一个特定的大小。我想保持这个大小相同,但增加它周围的命中区域而不会扭曲按钮的外观。

+2

你就不能点击并拖动的角落故事板内的UIButton增加尺寸? – user3746428 2014-10-06 21:52:50

+0

@ user3746428增加按钮尺寸也增加了我为按钮设置的背景颜色。我想保持按钮看起来与现在完全相同,但增加了它周围的命中区域。感谢您提到这一点,我会更新我的问题。 – 2014-10-06 21:54:58

+0

@JimBak你可以在UIView上创建一个UITapGestureRecognizer,并确定它是否在按钮附近。 – WMios 2014-10-06 21:59:00

回答

2

要增加命中区域而不扭曲背景颜色或图像,最简单的方法就是将它们分开。在提供视觉效果的UIView(或UIImage等)之上有一个清晰的UIButton,没有背景色。这样,你可以做任何你想要的UIButton的框架,它不会影响视觉效果,除非你应用相同的转换到其他UIView。

至于为什么该行代码不起作用,在CGRectMake第三和第四元素不是利润,他们是尺寸:你不能有一个负的高度和宽度。输入您想要的最终大小,而不是更改或边距(即,如果要将宽度缩小20,输入80)。

+1

谢谢你的澄清。我真的不想在图像上放一个按钮,并且必须用它来管理自动布局。我不能相信有没有简单的方法来简单地增加一定数量的像素按钮的命中区域... – 2014-10-06 22:42:35

2

子类UIButton并实现backgroundRectForBounds方法。

将框架展开至所需的触摸区域大小,然后通过添加插图来缩小背景的边界。

- (CGRect)backgroundRectForBounds:(CGRect)bounds { 
    return CGRectInset(bounds, -50, -50); 
} 

此处了解详情: https://developer.apple.com/library/ios/documentation/uikit/reference/uibutton_class/index.html#//apple_ref/occ/instm/UIButton/backgroundRectForBounds

+0

我试过这个,应该这样做,因为它不是。 CGFloat margin = 120.0; CGRect area = CGRectInset(button.bounds,-margin,-margin); [button backgroundRectForBounds:area]; – 2014-10-06 22:40:52

+0

在你的backgroundRectForBounds方法中添加一个断点以查看它是否被调用。 – dfmuir 2014-10-06 22:50:09

+0

是的,它被调用。 – 2014-10-06 22:57:08

5

我觉得你只是想使用相同的按钮限制背景颜色或回地面图像相同的面积,增加触摸区域?

根据我的知识,你不能在界面构建器中做到这一点。但是通过编码你可以通过使用图层。按钮

CALayer *buttonlayer=[CALayer layer]; 

    buttonlayer.frame=CGRectMake(50 , 50, 50, 50); // set the frame where you want to see the background color or background image to be visible in your button 

    buttonlayer.backgroundColor=[[UIColor colorWithPatternImage:[UIImage imageNamed:@"yourimage.png"] ] CGColor]; // if u want image (but remember the image size must same as your layer frame it may look bad if the image bounds does not mach your layer bounds, because you are setting color not image) 


    // to set color (donot use if you want image, use colorWithPatternImage to set image color) 
    buttonlayer.backgroundColor=[[UIColor graycolor] CGColor]; // if you want only color 

    // you can add round rects to the button layer 

    buttonlayer.cornerRadius=2.5f; 

    [yourbutton.layer addSublayer:buttonlayer]; 

取出口我就是你正在寻找不知道,因为我希望这可以帮助您,但检查一下图片enter image description here