Using Tim C's answer, I was able to create an extension on UIButton using Swift, which allows you to specify an image frame using .setImage() with the optional 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 want to set a frame from UIButton to CGRectMake(0, 0, 64, 64) and set its image to myImage with a CGRectMake(8, 8, 48, 48) frame CGRectMake(8, 8, 48, 48) , you can use
let button: UIButton = UIButton(frame: CGRectMake(0, 0, 64, 64)) button.setImage( myImage, inFrame: CGRectMake(8, 8, 48, 48), forState: UIControlState.Normal )
Jojodmo Dec 09 '15 at 4:35 2015-12-09 04:35
source share