Setting UISearchBar's search field background image changes the padding - ios

When I set a search field background image on a UIImage, the padding between the magnifying glass and placeholder text in the search bar when selected changes.
With the default background:
With a custom background:
This change is caused by these two lines:
UIImage *colorImage = [UIImage imageWithColor:[UIColor grayColor] size:CGSizeMake(28, 28)];
[self setSearchFieldBackgroundImage:[colorImage imageWithRoundedCorners:5] forState:UIControlStateNormal];
imageWithRoundedCorners: is a category method that simply draws the image onto a CALayer with a corner radius and then creates a UIImage from the graphics context.
Why is this and how can I avoid this? I tried passing an explicitly resizable image, but that had no effect.

Its odd that it resets it, however you can use something like this to set it to your liking after setting the background image. searchTextPositionAdjustment is a property on UISearchBar and works perfectly. 8.0 seems to be the default, but you could set it to whatever you like.
[self.searchBar setSearchFieldBackgroundImage:[self imageWithColor:[UIColor grayColor] andSize:CGSizeMake(28.0, 28.0)] forState:UIControlStateNormal];
[self.searchBar setSearchTextPositionAdjustment:UIOffsetMake(8.0, 0.0)];

For all those now using Swift, you can use the following code (works in Swift 2)
let searchBarBackground = UIImage.roundedImage(UIImage.imageWithColor(UIColor.whiteColor(), size: CGSize(width: 28, height: 28)),cornerRadius: 2)
searchBar.setSearchFieldBackgroundImage(searchBarBackground, forState: .Normal)
searchBar.searchTextPositionAdjustment = UIOffsetMake(8.0, 0.0)
Use this with an extension to UIImage:
extension UIImage {
class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect: CGRect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
class func roundedImage(image: UIImage, cornerRadius: Int) -> UIImage {
let rect = CGRect(origin:CGPoint(x: 0, y: 0), size: image.size)
UIGraphicsBeginImageContextWithOptions(image.size, false, 1)
UIBezierPath(
roundedRect: rect,
cornerRadius: CGFloat(cornerRadius)
).addClip()
image.drawInRect(rect)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
To give something looking like this:

Updated solution for Swift 4
searchTextPositionAdjustment = UIOffset(horizontal: 8.0, vertical: 0.0)

Related

ios UIImageRenderingModeAlwaysTemplate doesn't ignore opacity

I am trying to dynamically change the color and opacity of the images given to me by the designer. Of course, it works seamlessly with the following code :
_imgViewForMenu.tintColor = [_lblForMenu.textColor colorWithAlphaComponent:1.0f];
// This alpha component wont affect the png image with 38% opacity.
// You will never get full black image with [UIColor blackColor]
// and alpha component 1.0
_imgViewForMenu.image = [imageForMenuIcon imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
This will work, but only when the image has no opacity of its own. Else as said in the comment for the code, it wont work.
So the question is, how do you render an image to ignore both its color component as well as opacity. The system controls like UITabBar and UIBarButonItem seem to do it with ease. Why not with UIImageView then?
Try this:
extension UIImage {
func tinted(with color: UIColor) -> UIImage? {
let image = withRenderingMode(.alwaysTemplate)
UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
color.set()
image.draw(in: CGRect(x: 0.0, y: 0.0, width: image.size.width, height: image.size.height))
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage
}
}

Set background color of active tab bar item in Swift

I'm hoping to accomplish this without the use of images, if at all possible. Is there a way to create the effect shown in the image programmatically without have to render each tab out as an image?
Every question I've reviewed on SO has the tabs saved as JPGs, which is more work than I feel it should be.
Any ideas?
I took a similar approach to #matcartmill but without the need for a special image. This solution is just based on your color.
// set red as selected background color
let numberOfItems = CGFloat(tabBar.items!.count)
let tabBarItemSize = CGSize(width: tabBar.frame.width / numberOfItems, height: tabBar.frame.height)
tabBar.selectionIndicatorImage = UIImage.imageWithColor(color: UIColor.red, size: tabBarItemSize).resizableImage(withCapInsets: UIEdgeInsets.zero)
// remove default border
tabBar.frame.size.width = self.view.frame.width + 4
tabBar.frame.origin.x = -2
I'm making use of the following extension of UIImage:
extension UIImage {
class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect: CGRect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
I hope this helps!
for swift 4
extension UIImage {
class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect: CGRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
Update to SWIFT 3:
let numberOfItems = CGFloat((tabBarController?.tabBar.items!.count)!)
let tabBarItemSize = CGSize(width: (tabBarController?.tabBar.frame.width)! / numberOfItems,
height: (tabBarController?.tabBar.frame.height)!)
tabBarController?.tabBar.selectionIndicatorImage
= UIImage.imageWithColor(color: UIColor.black,
size: tabBarItemSize).resizableImage(withCapInsets: .zero)
tabBarController?.tabBar.frame.size.width = self.view.frame.width + 4
tabBarController?.tabBar.frame.origin.x = -2
extension UIImage
{
class func imageWithColor(color: UIColor, size: CGSize) -> UIImage
{
let rect: CGRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
So here's what I ended up doing. It's a mix of using a 640x49 PNG that's the color of the blue "highlighted" background I need.
In AppDelegate.swift:
var selectedBG = UIImage(named:"tab-selected-full")?.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 0, 0, 0))
UITabBar.appearance().selectionIndicatorImage = selectedBG
And then in the first View Controller that gets loaded, I have:
tabBarController?.tabBar.frame.size.width = self.view.frame.width+4
tabBarController?.tabBar.frame.origin.x = -2
The reason for the above two lines is that, by default, Apple has a 2px border between the left and right sides of the tab bar and the tab bar items.
In the above I simply make the tab bar 4px wider, and then offset it so the border on the left falls just outside of the view, thus the border on the right will also fall outside of the view.

How can I change image tintColor

I'm receiving image from a server, then based on a color chosen by the user, the image color will be changed.
I tried the following :
_sketchImageView.image = [_sketchImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[_sketchImageView setTintColor:color];
i got the opposite of my goal (the white color outside UIImage is colored with the chosen color).
what is going wrong?
i need to do the same in this question,the provided solution doesn't solve my case.
How can I change image tintColor in iOS and WatchKit
Try to generate new image for yourself
UIImage *newImage = [_sketchImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
UIGraphicsBeginImageContextWithOptions(image.size, NO, newImage.scale);
[yourTintColor set];
[newImage drawInRect:CGRectMake(0, 0, image.size.width, newImage.size.height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
_sketchImageView.image = newImage;
And use it.
Good luck
======= UPDATE =======
This solution will only change color of all pixel's image.
Example: we have a book image: http://pngimg.com/upload/book_PNG2113.png
And after running above code (exp: TintColor is RED). We have:
SO: how your image is depends on how you designed it
In Swift you can use this extension: [Based on #VietHung's objective-c solution]
Swift 5:
extension UIImage {
func imageWithColor(color: UIColor) -> UIImage? {
var image = withRenderingMode(.alwaysTemplate)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
color.set()
image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
Previous Swift version:
extension UIImage {
func imageWithColor(color: UIColor) -> UIImage? {
var image = imageWithRenderingMode(.AlwaysTemplate)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
color.set()
image.drawInRect(CGRect(x: 0, y: 0, width: size.width, height: size.height))
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
In swift 2.0 you can use this
let image = UIImage(named:"your image name")?.imageWithRenderingMode(.AlwaysTemplate)
let yourimageView.tintColor = UIColor.redColor()
yourimageView.image = image
In swift 3.0 you can use this
let image = UIImage(named:"your image name")?.withRenderingMode(.alwaysTemplate)
let yourimageView.tintColor = UIColor.red
yourimageView.image = image
Try something like this
UIImage *originalImage = _sketchImageView.image
UIImage *newImage = [originalImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,50,50)]; // your image size
imageView.tintColor = [UIColor redColor]; // or whatever color that has been selected
imageView.image = newImage;
_sketchImageView.image = imageView.image;
Hope this helps.
In Swift 3.0 you can use this extension: [Based on #VietHung's objective-c solution]
extension UIImage {
func imageWithColor(_ color: UIColor) -> UIImage? {
var image = imageWithRenderingMode(.alwaysTemplate)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
color.set()
image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
For Swift 3.0, I made a custom subclass of UIImageView called TintedUIImageView. Now the image uses whatever tint color is set in interface builder or code
class TintedUIImageView: UIImageView {
override func awakeFromNib() {
if let image = self.image {
self.image = image.withRenderingMode(.alwaysTemplate)
}
}
}
You can try:
_sketchImageView.image = [self imageNamed:#"imageName" withColor:[UIColor blackColor]];
- (UIImage *)imageNamed:(NSString *)name withColor:(UIColor *)color
{
// load the image
//NSString *name = #"badge.png";
UIImage *img = [UIImage imageNamed:name];
// begin a new image context, to draw our colored image onto
UIGraphicsBeginImageContext(img.size);
// get a reference to that context we created
CGContextRef context = UIGraphicsGetCurrentContext();
// set the fill color
[color setFill];
// translate/flip the graphics context (for transforming from CG* coords to UI* coords
CGContextTranslateCTM(context, 0, img.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// set the blend mode to color burn, and the original image
CGContextSetBlendMode(context, kCGBlendModeColorBurn);
CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
CGContextDrawImage(context, rect, img.CGImage);
// set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
CGContextClipToMask(context, rect, img.CGImage);
CGContextAddRect(context, rect);
CGContextDrawPath(context,kCGPathFill);
// generate a new UIImage from the graphics context we drew onto
UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//return the color-burned image
return coloredImg;
}
Try setting the tint color on the superview of the image view. E.g. [self.view setTintColor:color];
in Swift 4 you can simply make an extension like that:
import UIKit
extension UIImageView {
func tintImageColor(color: UIColor) {
guard let image = image else { return }
self.image = image.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
self.tintColor = color
}
}
- SWIFT 4
extension UIImage {
func imageWithColor(_ color: UIColor) -> UIImage? {
var image: UIImage? = withRenderingMode(.alwaysTemplate)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
color.set()
image?.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Here's how I apply and use tints in IOS 9 with Swift.
//apply a color to an image
//ref - http://stackoverflow.com/questions/28427935/how-can-i-change-image-tintcolor
//ref - https://www.captechconsulting.com/blogs/ios-7-tutorial-series-tint-color-and-easy-app-theming
func getTintedImage() -> UIImageView {
var image : UIImage;
var imageView : UIImageView;
image = UIImage(named: "someAsset")!;
let size : CGSize = image.size;
let frame : CGRect = CGRectMake((UIScreen.mainScreen().bounds.width-86)/2, 600, size.width, size.height);
let redCover : UIView = UIView(frame: frame);
redCover.backgroundColor = UIColor.redColor();
redCover.layer.opacity = 0.75;
imageView = UIImageView();
imageView.image = image.imageWithRenderingMode(UIImageRenderingMode.Automatic);
imageView.addSubview(redCover);
return imageView;
}
One thing you can do is, just add your images to Assets folder in XCode and then change the rendering mode to Template Image, so whenever you change the tint color of UIImageView, it will automatically makes change to image.
Check this link out -> https://www.google.co.in/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&ved=0ahUKEwiM0YXO0ejTAhUIQ48KHfGpBpgQjRwIBw&url=https%3A%2F%2Fkrakendev.io%2Fblog%2F4-xcode-asset-catalog-secrets-you-need-to-know&psig=AFQjCNGnAzVn92pCqM8612o1R0J9q1y7cw&ust=1494619445516498
let image = UIImage(named: "i m a g e n a m e")?.withRenderingMode(.alwaysTemplate)
imageView.tintColor = UIColor.white // Change to require color
imageView.image = image
Try this
iOS 13.4 and above
UIImage *image = [UIImage imageNamed:#"placeHolderIcon"];
[image imageWithTintColor:[UIColor whiteColor] renderingMode: UIImageRenderingModeAlwaysTemplate];

Change color of png in buttons - ios

I've got a set of icons that I've created that are transparent white PNGs:
And what I'd like to do is be able to tint them to other colors. Such as blue, grey, etc.
I've noticed that 'clicked/tapped' they change automatically to a grey. So I assume I can change that grey to whatever I like either with a tap or its normal state:
What would be the best way to achieve this?
Following code will set tint colour for normal state of button:
For Swift 4 and newer:
let origImage = UIImage(named: "imageName")
let tintedImage = origImage?.withRenderingMode(.alwaysTemplate)
btn.setImage(tintedImage, for: .normal)
btn.tintColor = .red
You can change tint colour according to your need when state changes for button.
Older versions
For Swift 3:
let origImage = UIImage(named: "imageName")
let tintedImage = origImage?.withRenderingMode(.alwaysTemplate)
btn.setImage(tintedImage, forState: .normal)
btn.tintColor = .redColor
For Swift 2:
see revision history.
I found the easiest approach below,
Open assetcatalog and select the image then go to attributes inspector and change Render As to Template Image as below
Then add below code in button Action method
yourButton.tintColor = .gray
Swift 4 or 5
extension UIButton{
func setImageTintColor(_ color: UIColor) {
let tintedImage = self.imageView?.image?.withRenderingMode(.alwaysTemplate)
self.setImage(tintedImage, for: .normal)
self.tintColor = color
}
}
Use:
button.setImage(UIImage(named: "image_name"), for: .normal) // You can set image direct from Storyboard
button.setImageTintColor(UIColor.white)
iOS 7 introduced a property called tintColor for views (including UIImageView). However you also need to set the rendering type on the UIImage for this to have any effect.
UIImage *originalImage = [UIImage imageNamed:#"image.png"];
UIImage *tintedImage = [originalImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
UIImageView *imageView = [[UIImageView alloc] initWithImage:tintedImage];
imageView.tintColor = [UIColor grayColor];
[self.view addSubview:imageView];
This should produce the effect you are after in a default state.
If you are setting the image for a button, just go to attributes inspector and change the button type to system. Then set the image and change the tint color. The color of the image will change. If it did not take place, check the button type.
For change tint of image (pick, classical image, photo) use that :
Example image :
Swift 2
public extension UIImage {
/**
Tint, Colorize image with given tint color<br><br>
This is similar to Photoshop's "Color" layer blend mode<br><br>
This is perfect for non-greyscale source images, and images that have both highlights and shadows that should be preserved<br><br>
white will stay white and black will stay black as the lightness of the image is preserved<br><br>
<img src="http://yannickstephan.com/easyhelper/tint1.png" height="70" width="120"/>
**To**
<img src="http://yannickstephan.com/easyhelper/tint2.png" height="70" width="120"/>
- parameter tintColor: UIColor
- returns: UIImage
*/
public func tintPhoto(tintColor: UIColor) -> UIImage {
return modifiedImage { context, rect in
// draw black background - workaround to preserve color of partially transparent pixels
CGContextSetBlendMode(context, .Normal)
UIColor.blackColor().setFill()
CGContextFillRect(context, rect)
// draw original image
CGContextSetBlendMode(context, .Normal)
CGContextDrawImage(context, rect, self.CGImage)
// tint image (loosing alpha) - the luminosity of the original image is preserved
CGContextSetBlendMode(context, .Color)
tintColor.setFill()
CGContextFillRect(context, rect)
// mask by alpha values of original image
CGContextSetBlendMode(context, .DestinationIn)
CGContextDrawImage(context, rect, self.CGImage)
}
}
/**
Tint Picto to color
- parameter fillColor: UIColor
- returns: UIImage
*/
public func tintPicto(fillColor: UIColor) -> UIImage {
return modifiedImage { context, rect in
// draw tint color
CGContextSetBlendMode(context, .Normal)
fillColor.setFill()
CGContextFillRect(context, rect)
// mask by alpha values of original image
CGContextSetBlendMode(context, .DestinationIn)
CGContextDrawImage(context, rect, self.CGImage)
}
}
/**
Modified Image Context, apply modification on image
- parameter draw: (CGContext, CGRect) -> ())
- returns: UIImage
*/
private func modifiedImage(#noescape draw: (CGContext, CGRect) -> ()) -> UIImage {
// using scale correctly preserves retina images
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context: CGContext! = UIGraphicsGetCurrentContext()
assert(context != nil)
// correctly rotate image
CGContextTranslateCTM(context, 0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
let rect = CGRectMake(0.0, 0.0, size.width, size.height)
draw(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
UPD
Swift 3
extension UIImage {
/**
Tint, Colorize image with given tint color<br><br>
This is similar to Photoshop's "Color" layer blend mode<br><br>
This is perfect for non-greyscale source images, and images that have both highlights and shadows that should be preserved<br><br>
white will stay white and black will stay black as the lightness of the image is preserved<br><br>
<img src="http://yannickstephan.com/easyhelper/tint1.png" height="70" width="120"/>
**To**
<img src="http://yannickstephan.com/easyhelper/tint2.png" height="70" width="120"/>
- parameter tintColor: UIColor
- returns: UIImage
*/
func tintPhoto(_ tintColor: UIColor) -> UIImage {
return modifiedImage { context, rect in
// draw black background - workaround to preserve color of partially transparent pixels
context.setBlendMode(.normal)
UIColor.black.setFill()
context.fill(rect)
// draw original image
context.setBlendMode(.normal)
context.draw(cgImage!, in: rect)
// tint image (loosing alpha) - the luminosity of the original image is preserved
context.setBlendMode(.color)
tintColor.setFill()
context.fill(rect)
// mask by alpha values of original image
context.setBlendMode(.destinationIn)
context.draw(context.makeImage()!, in: rect)
}
}
/**
Tint Picto to color
- parameter fillColor: UIColor
- returns: UIImage
*/
func tintPicto(_ fillColor: UIColor) -> UIImage {
return modifiedImage { context, rect in
// draw tint color
context.setBlendMode(.normal)
fillColor.setFill()
context.fill(rect)
// mask by alpha values of original image
context.setBlendMode(.destinationIn)
context.draw(cgImage!, in: rect)
}
}
/**
Modified Image Context, apply modification on image
- parameter draw: (CGContext, CGRect) -> ())
- returns: UIImage
*/
fileprivate func modifiedImage(_ draw: (CGContext, CGRect) -> ()) -> UIImage {
// using scale correctly preserves retina images
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context: CGContext! = UIGraphicsGetCurrentContext()
assert(context != nil)
// correctly rotate image
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
draw(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
You can use this extension:
import UIKit
extension CGContext {
func fill(_ rect: CGRect,
with mask: CGImage,
using color: CGColor) {
saveGState()
defer { restoreGState() }
translateBy(x: 0.0, y: rect.size.height)
scaleBy(x: 1.0, y: -1.0)
setBlendMode(.normal)
clip(to: rect, mask: mask)
setFillColor(color)
fill(rect)
}
}
extension UIImage {
func filled(with color: UIColor) -> UIImage {
let rect = CGRect(origin: .zero, size: self.size)
guard let mask = self.cgImage else { return self }
if #available(iOS 10.0, *) {
let rendererFormat = UIGraphicsImageRendererFormat()
rendererFormat.scale = self.scale
let renderer = UIGraphicsImageRenderer(size: rect.size,
format: rendererFormat)
return renderer.image { context in
context.cgContext.fill(rect,
with: mask,
using: color.cgColor)
}
} else {
UIGraphicsBeginImageContextWithOptions(rect.size,
false,
self.scale)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { return self }
context.fill(rect,
with: mask,
using: color.cgColor)
return UIGraphicsGetImageFromCurrentImageContext() ?? self
}
}
}
If you use asset catalogs you can set the image asset itself to render in template mode. After that you can set the tintColor of the button in Interface Builder (or in code) and it should take.
Swift 4
let origImage = UIImage(named: "check")
let tintedImage = origImage?.withRenderingMode(.alwaysTemplate)
buttons[0].setImage(tintedImage, for: .normal)
buttons[0].tintColor = .red
If you use asset catalogs you can set the image asset itself to render in template mode. After that you can set the tintColor of the button in Interface Builder (or in code) and it should take.
Swift 4 and 4.2
let img = UIImage.init(named: "buttonName")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
btn.setImage(img, for: .normal)
btn.tintColor = .gray

UIButton with rounded rects and custom backgroundImage when highlighted

The problem is that my button doesn't get displayed correctly when highlighted. I'd like the background image to be blue, not opaque. The code I use is presented below.
self.button.layer.borderWidth = 1.0
self.button.layer.borderColor = self.button.tintColor?.CGColor
self.button.layer.cornerRadius = 5.0
self.button.layer.masksToBounds = true
self.button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
self.button.setBackgroundImage(self.imageWithColor(self.button.tintColor!, size: self.button.bounds.size), forState: UIControlState.Highlighted)
And the method for getting an image with a color.
func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, true, 1.0)
color.setFill()
var bounds = CGRectMake(0, 0, size.width, size.height)
UIRectFill(bounds)
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
return image;
}

Resources