I have made the UIButton
programmatically
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];
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.
[togglebutton setImageEdgeInsets: UIEdgeInsetsMake( 0, -30, 0, -25)];
I tried to set the image inset
but it making the image irregular
. Please look upon this issue.
Programmatically. To make a multi-line text in UIButton, you insert a new line character ( \n ) wherever you want in button title and set lineBreakMode to byWordWrapping . You can adjust text alignment with . textAlignment .
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With