With the help of Tim C's answer, I was able to create an extension on UIButton
using Swift that allows you to specify the image frame by using the .setImage()
function with an extra frame
parameter
extension UIButton{
func setImage(image: UIImage?, inFrame frame: CGRect?, forState state: UIControlState){
self.setImage(image, forState: state)
if let frame = frame{
self.imageEdgeInsets = UIEdgeInsets(
top: frame.minY - self.frame.minY,
left: frame.minX - self.frame.minX,
bottom: self.frame.maxY - frame.maxY,
right: self.frame.maxX - frame.maxX
)
}
}
}
Using this, if you wanted to set the frame of a UIButton
to CGRectMake(0, 0, 64, 64)
, and set the image of it to myImage
with a frame of CGRectMake(8, 8, 48, 48)
, you could use
let button: UIButton = UIButton(frame: CGRectMake(0, 0, 64, 64))
button.setImage(
myImage,
inFrame: CGRectMake(8, 8, 48, 48),
forState: UIControlState.Normal
)