preface

During the development process, we often encounter UIButton click area is too small and we don’t want to change the size of the button.

Today’s article will share the code that solves this problem

Implementation approach

  • Subclass UIButton overwrite ithitTest:methods
  • Subclass UIButton override point: Inside :withEvent: method

The first way

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
	let biggerButtonFrame = theButton.frame.insetBy(dx: -30, dy: -30) // 1	
	if biggerButtonFrame.contains(point) { // 2
		return theButton // 3
	}		
	return super.hitTest(point, with: event) // 4
}
Copy the code
    1. Make theButton’s x larger by 30 and y larger by 30. And then it’s 2 by 30 and 2 by 30.)
    1. Determine whether the click position is within the enlarged frame.
    1. If so, return button
    1. If not, let the event continue

Note: there is no judgment theButton. Alpha = = 0 and theButton. UserInterface.. == YES and whether it is visible or not, use your own judgment

The second way

Overwrite UIView’s point: method

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
	let biggerFrame = bounds.insetBy(dx: -30, dy: -30)

	return biggerFrame.contains(point)
}
Copy the code

The OC version looks like this

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {CGRectInset(<#CGRect #>, <#CGFloat dx#>, <#CGFloat dy#>) ... }Copy the code

But the second method is actually hitTest: the UIView judgment before the method is called, which determines whether the currently clicked point is on that UIView.

However, the first method is recommended

The core code

In fact, the core code is

CGRectInset(<#CGRect rect#>, <#CGFloat dx#>, <#CGFloat dy#>)

CGRect CGRectOffset(CGRect rect, CGFloat dx, CGFloat dy) is centered on RECt and is scaled according to dx and dy.

If dx and dy are negative then they are amplified and positive numbers are reduced

But you might be wondering how to zoom in on the width and height

First of all, let’s make it clear that this API is going to scale as soon as we pass in a positive number and then the width and the height will be appropriate to the dx and dy that we passed in to determine the scale ratio

It’s going to be X 2 because I’m scaling in the center, because I have both sides, so I’m going to shrink by 30 on the left and I’m going to shrink by 30 on the right, so the top and the bottom are the same thing.

Look it up on Google

Refer to Increasing the tap area of a UIButton

See the iOS Touch event family bucket

Citation: Original address