简体   繁体   中英

How to create a small button with a large tappable area

I want to create a close button which will look like a circle with an x in the middle. In x code I set the button's size and width to be large so that the touchable area is larger (50 x 50 with a font of just 22).

I create a button, change the title to X and then set the following:

[self.closeButton.layer setBorderWidth:2.0f];
[self.closeButton.layer setBorderColor:[[UIColor whiteColor] CGColor]];
[self.closeButton.layer setCornerRadius:self.closeButton.bounds.size.width/2];

The circle border is too far from the X. How would I bring the borders in tighter to the X but not decrease the size of the clickable area?

assign image to a button. and make tappable area as you want. then set image location in button by setting inset value of that button as top, bottom, left, right. change the value of this according to your requirements. You can set inset value from interface builder as shown in image here. change the value and see the difference to place your image in button at exact location you want.

设置插图

exactly like this image

设置带有更多可点击区域的插图

I'd suggest exactly what Max has done. He has shown how to do this via IB, this is how you do it through code:

myButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 25, 25);// UIButton

myBarButtonItem.imageInsets = UIEdgeInsetsMake(0, 0, 25, 25);// UIBarButtonItem

EDIT:

Sorry for not reading your question properly the first time. I think you will run into the same issue with this approach : the border/cornerRadius of the button will not respect any insets. It will be drawn according to the frame of the button. Only (easy) workaround at the top of my head, is to create an image with the border and corners in it, and then set it as the image. The image will respect the insets, and you will have your desired tappable area, with the borders exactly where you want them.

There might be a more elegant workaround through subclassing, but unless you change the border width/color, or corner radius of your button at any stage, I'd suggest sticking with custom image.

EDIT 2:

Instead of using an image you might want to use this unicode character .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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