ios 如何增加UIButton的选择区域?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17249104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:02:40  来源:igfitidea点击:

How to increase selection area of UIButton?

iosobjective-cuibutton

提问by Minkle Garg

I have made the UIButtonprogrammatically

我已经以UIButton编程方式

togglebutton = [UIButton buttonWithType:UIButtonTypeCustom];
togglebutton.frame = CGRectMake(42, 15, 80, 21);
[togglebutton addTarget:self action:@selector(toggleview)   
forControlEvents:UIControlEventTouchUpInside];
[togglebutton setImage:[UIImage imageNamed:@"squ.png"] forState:UIControlStateNormal];
[buttonView addSubview:togglebutton];

enter image description here

enter image description here

It is looked as the right button in above image. Now the requirement is that the selection area of this button should be more than then the uibutton image. So that the user will be able to click the button easily by touching on near by area of particular button.

它看起来像上图中的右侧按钮。现在的要求是这个按钮的选择区域应该大于uibutton图像。这样用户就可以通过触摸特定按钮的附近区域轻松点击按钮。

[togglebutton setImageEdgeInsets: UIEdgeInsetsMake( 0, -30, 0, -25)];

I tried to set the image insetbut it making the image irregular. Please look upon this issue.

我试图设置,image inset但它使image irregular. 请看一下这个问题。

回答by Nitin Gohel

You can achieve this by setting the button's contentEdgeInsets, for example:

您可以通过设置按钮的 来实现这一点contentEdgeInsets,例如:

toggleButton.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0); //set as you require 

回答by Mark

For Swift

对于斯威夫特

You can override func 'pointInside' of UIView class to expand clickable area.

您可以覆盖 UIView 类的 func 'pointInside' 以扩展可点击区域。

override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
    // padding : local variable of your custom UIView, CGFloat
    // you can change clickable area dynamically by setting this value.

    let newBound = CGRect(
        x: self.bounds.origin.x - padding,
        y: self.bounds.origin.y - padding,
        width: self.bounds.width + 2 * padding,
        height: self.bounds.height + 2 * padding
    )
    return CGRectContainsPoint(newBound, point)
}

Use like this,

像这样使用,

class MyButton: UIButton {
    var padding = CGFloat(0) // default value

    //func pointInside at here!!
}

When you init your button, set your custom padding.

当你初始化你的按钮时,设置你的自定义填充。

func initButton() {
    let button = MyButton(frame: CGRect(x: 100, y: 100, width: 30, height: 30))
    button.padding = 10 // any value you want
    view.addSubview(button)
}

then your button is in frame (x: 100, y:100, width: 30, height: 30)

那么你的按钮在框架中(x:100,y:100,宽度:30,高度:30)

and your button's clickable area might be in the frame with (x: 90, y: 90, width: 50, height: 50)

并且您的按钮的可点击区域可能位于 (x: 90, y: 90, width: 50, height: 50) 的框架中

** Be sure to check overlapping with any other view, because its clickable area is larger than it looks.

** 请务必检查是否与任何其他视图重叠,因为它的可点击区域比看起来要大。

Update for Swift 3

Swift 3 更新

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    let padding = CGFloat(10)
    let extendedBounds = bounds.insetBy(dx: -padding, dy: -padding)
    return extendedBounds.contains(point)
}

回答by Adithya

Try using contentEdgeInsetsproperty of the UIButton.

尝试使用UIButton 的contentEdgeInsets属性。

回答by olidem

in xcode 9 you can do the following:

在 xcode 9 中,您可以执行以下操作:

xcode 9 screenshot

xcode 9 screenshot

that means you have to compensate the image offset and content offset to ensure a centered image positioning.

这意味着您必须补偿图像偏移和内容偏移以确保居中的图像定位。

回答by Suraj Sonawane

The Below code solves my problem.This is very basic way, Try this :

下面的代码解决了我的问题。这是非常基本的方法,试试这个:

    button.contentEdgeInsets = UIEdgeInsetsMake(15, 20, 10, 10);  //Change x,y,width,height as per your requirement.

回答by Syed Sadrul Ullah Sahad

For Objective C

对于目标 C

Create this custom UIButton Class and assign it into your button. Then set these properties values from viewController.

创建此自定义 UIButton 类并将其分配到您的按钮中。然后从 viewController 设置这些属性值。

//This is .h file
     #import <UIKit/UIKit.h>
        @interface CustomButton : UIButton
        @property (nonatomic) CGFloat leftArea;
        @property (nonatomic) CGFloat rightArea;
        @property (nonatomic) CGFloat topArea;
        @property (nonatomic) CGFloat bottomArea;
        @end



        //.m file is following
        #import "CustomButton.h
        @implementation CustomButton

        -(BOOL) pointInside:(CGPoint)point withEvent:(UIEvent *)event
        {
            CGRect newArea = CGRectMake(self.bounds.origin.x - _leftArea, self.bounds.origin.y - _topArea, self.bounds.size.width + _leftArea + _rightArea, self.bounds.size.height + _bottomArea + _topArea);

            return CGRectContainsPoint(newArea, point);
        }
        @end

回答by i.AsifNoor

In my case, my button image is small and I want to increase button area while not increasing uibuttonimage size because it will look blurred. So I increased button frame and then set button image setImageEdgeInsets. Positive values for edgeInsetswill shrink and negative values will expand.

就我而言,我的按钮图像很小,我想增加按钮区域而不增加uibutton图像大小,因为它看起来很模糊。所以我增加了按钮框架,然后设置了按钮图像setImageEdgeInsets。的正值edgeInsets将缩小,负值将扩大。

self.menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.menuButton addTarget:self
                  action:@selector(onSideBarButtonTapped:)
        forControlEvents:UIControlEventTouchDown];
[self.menuButton setImage:[UIImage imageNamed:@"menu"]
                         forState:UIControlStateNormal];
self.menuButton.frame = CGRectMake(10, 3, 40, 40);

Now I am going to shrink image size so that button will not look blurred.

现在我要缩小图像大小,这样按钮就不会看起来模糊了。

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

回答by kevinl

I would create a UIView around that button so that you can set the size to whatever you want. Then I'd set the UIView's background color to the clear color (do not set opacity to 0 or the gesture won't be recognized)

我会围绕该按钮创建一个 UIView,以便您可以将大小设置为您想要的任何值。然后我将 UIView 的背景颜色设置为清晰的颜色(不要将不透明度设置为 0 否则手势将无法识别)

Then add a UIGestureRecognizer to the uiview to handle the same IBAction

然后在uiview中添加一个UIGestureRecognizer来处理同一个IBAction

Of course, many people will encourage/prefer the use of the edgeInsets

当然,很多人会鼓励/更喜欢使用 edgeInsets

回答by Santosh

Here is an example of increasing touchable area of custom UIButton:

下面是增加自定义 UIButton 的可触摸区域的示例:

UIImage *ButtonImage=[UIImage imageNamed:@"myimage.png"];
UIButton *myButton=[UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame=CGRectMake(10, 25, ButtonImage.size.width/2+10, ButtonImage.size.height/2+10);
[myButton setImage:ButtonImage forState:UIControlStateNormal];
myButton.imageEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
[myButton addTarget:self action:@selector(crossButtonClick:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:myButton];

Hope it would be helpful.

希望它会有所帮助。