问题
I found out that UIButton
has a backgroundRect(forBounds:)
function, but I can not understand where and how can I use it.
I also cannot understand how can I use the contentRect(forBounds:)
, titleRect(forContentRect:)
and imageRect(forContentRect:)
methods. Please, explain me.
回答1:
By default, backgroundRect(forBounds:)
returns the same value as bounds
. However, you can override it in a subclass to prevent drawing over your custom content.
From Apple Developer Documentation:
The default implementation of this method returns the value in the bounds parameter. This rectangle represents the area in which the button draws its standard background content. Subclasses that provide custom background adornments can override this method and return a modified bounds rectangle to prevent the button from drawing over any custom content.
contentRect(forBounds:)
returns the area that is used for displaying the title and the image of the button.
titleRect(forContentRect:)
and imageRect(forContentRect:)
return the rectangle of the title/image.
Here is some visual help for the return value of all four of these methods for a non-overridden, standard button:
回答2:
But all the same I can not imagine a situation in which I will need to address this function
Then imagine this: a button that appears to shrink a little in response to being tapped, as feedback to the user, growing back to its normal size when the user's finger is no longer on the button. How would you do it? Here's an elegant way:
extension CGSize {
func sizeByDelta(dw:CGFloat, dh:CGFloat) -> CGSize {
return CGSize(width:self.width + dw, height:self.height + dh)
}
}
class MyShrinkingButton: UIButton {
override func backgroundRect(forBounds bounds: CGRect) -> CGRect {
var result = super.backgroundRect(forBounds:bounds)
if self.isHighlighted {
result = result.insetBy(dx: 3, dy: 3)
}
return result
}
override var intrinsicContentSize : CGSize {
return super.intrinsicContentSize.sizeByDelta(dw:25, dh: 20)
}
}
The effect is subtle but lively and clear. Here is the button in its normal state and in its highlighted state.
来源:https://stackoverflow.com/questions/50737542/what-is-the-method-backgroundrectforbounds-of-uibutton-used-for