xcode iOS增加UIButton命中区域

Jim*_*Bak 8 uibutton ios xcode6

我试图增加我的UIButton的命中区域.我有一个新的Xcode项目,在故事板的中心有一个UIButton.该按钮通过插座和动作连接到我的视图控制器.我可以通过编程方式更改按钮标题,只是为了好玩,当我点击按钮时,它的动作会改变视图的背景.所以我知道一切都是有联系和有效的.

从我在网上看到的,这应该有效,但事实并非如此.

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

有什么想法吗?我试过没有负边距,这也不起作用.顺便说一下,我已经尝试了很多地方这个问题,但它没有用.谢谢您的帮助.另外,我听说UIButton的子类化可能会产生一个问题,对此有何想法?

更新:我想制作的UIButton具有背景颜色并且是特定尺寸.我希望保持这个大小不变但增加它周围的命中区域而不会扭曲按钮的外观.

Smi*_*ile 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];
Run Code Online (Sandbox Code Playgroud)

我不确定你在寻找什么我希望这能帮助你,但是检查一下图像在此输入图像描述


Ner*_*ken 2

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

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