How to increase selection area of UIButton?
You can achieve this by setting the button's contentEdgeInsets
, for example:
toggleButton.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0); //set as you require
For Swift
You can override func 'pointInside' of UIView class to expand clickable area.
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)
and your button's clickable area might be in the frame with (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
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)}