Swift: Set UIButton Image with CGRect

1.5k views Asked by At

I'd like to set the image of a UIButton, but without creating all of the assets at different sizes.

Since it should be just a grey rectangle, with some text on top, I'm trying to do this by creating a CGRect. The title is displayed as desired, and the button can be clicked for the region described by the CGRect, but when I run the app, nothing can be seen, except for the title. I tried to fix this by setting the tintColor, but to no avail.

Here's what I have so far.

@IBOutlet weak var swapButton: UIButton! 

In viewDidLoad():

var rectangle = CGRectMake(0, 0, view.layer.frame.width, 20)
UIGraphicsBeginImageContext(rectangle.size)
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), rectangle.origin.x, rectangle.origin.y)
var rectangle2 = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

swapButton.setBackgroundImage(rectangle2, forState: .Normal)
swapButton.tintColor = UIColor.blackColor()

Is there any way to accomplish this?

1

There are 1 answers

0
Ashish Kakkad On BEST ANSWER

Try this code :

var yourbutton = UIButton(frame:CGRectMake(100, 100, 100, 35))

var rect  = CGRectMake(0, 0, 1, 1)
UIGraphicsBeginImageContext(rect.size)
var context : CGContextRef  = UIGraphicsGetCurrentContext()

CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)
CGContextFillRect(context, rect)

var image : UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

yourbutton.setBackgroundImage(image, forState: UIControlState.Normal)

self.view.addSubview(yourbutton)