[英]Center UIButton image with inset
I'd like to create a UIButton, but with a larger tap area than the image. 我想创建一个UIButton,但是比图像有更大的拍子区域。 (Ex: 40x40 button, but the image is only 20x20, centered).
(例如:40x40按钮,但图像仅为20x20,居中)。
Is that what imageEdgeInsets
is for? 这是
imageEdgeInsets
的用途吗?
I've set it both programatically: (This is in the UIView which contains my button) 我已经以编程方式设置它:(这是在包含我的按钮的UIView中)
- (void)awakeFromNib {
[_plusButton setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
[_plusButton setContentMode:UIViewContentModeCenter];
}
And from storyboard 并从故事板
But neither of them seem to work. 但它们似乎都不起作用。
Got it I think that you set your image as a background image of the button, set it as a image then it will never stretches(remains in it original shape) and imageEdgeInsets
will works on it properly. 知道了我认为您将图像设置为按钮的背景图像,将其设置为图像然后它将永远不会拉伸(保持原始形状)并且
imageEdgeInsets
将正常工作。
Like: 喜欢:
Here is a simple example of how to use imageEdgeInsets This will make a 20x20 button with a hittable area 10 pixels bigger all the way around (40x40) 下面是一个如何使用imageEdgeInsets的简单示例。这将生成一个20x20的按钮,其可击中区域一直大于10像素(40x40)
var expandHittableAreaAmt: CGFloat = 10
var buttonWidth: CGFloat = 20
var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
button.frame = CGRectMake(0, 0,
buttonWidth + expandHittableAreaAmt*2,
buttonWidth + expandHittableAreaAmt*2)
button.imageEdgeInsets = UIEdgeInsetsMake(expandHittableAreaAmt,
expandHittableAreaAmt, expandHittableAreaAmt, expandHittableAreaAmt)
button.setImage(UIImage(named: "buttonImage"), forState: .Normal) //20x20 image
button.addTarget(self, action: "didTouchButton:", forControlEvents: .TouchUpInside)
Swift 3 & 4 Solution programmatically. Swift 3&4解决方案以编程方式。
buttonOutlet.setImage(UIImage(name: "iconWhite"), for: .normal)
buttonOutlet.imageEdgeInsets = UIEdgeInsets(top: 10, left:10, bottom: 10, right: 10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.