I believe the UIControlState you're actually looking for is Focused
rather than Highlighted
.
Here's an example of how to change the backgroundColor
and titleColor
of a UIButton
when it becomes focused. (Accomplished with the help of this answer):
import UIKit
class ViewController: UIViewController {
let myButton = UIButton(type: UIButtonType.Custom)
let myOtherButton = UIButton(type: UIButtonType.Custom)
override func viewDidLoad() {
super.viewDidLoad()
// Button we will change on focus
myButton.frame = CGRectMake(view.frame.midX - 300, view.frame.midY, 400, 100)
myButton.setTitle("myButton", forState: .Normal)
// Normal
myButton.backgroundColor = UIColor.whiteColor()
myButton.setTitleColor(UIColor.orangeColor(), forState: .Normal)
// Focused
myButton.setBackgroundImage(imageWithColor(UIColor.orangeColor()), forState: .Focused)
myButton.setTitleColor(UIColor.whiteColor(), forState: .Focused)
view.addSubview(myButton)
// Other button so we can change focus // Just for example
myOtherButton.frame = CGRectMake(view.frame.midX + 300, view.frame.midY, 400, 100)
myOtherButton.setTitle("myOtherButton", forState: .Normal)
// Normal
myOtherButton.backgroundColor = UIColor.whiteColor()
myOtherButton.setTitleColor(UIColor.orangeColor(), forState: .Normal)
// Focused
myOtherButton.setBackgroundImage(imageWithColor(UIColor.orangeColor()), forState: .Focused)
myOtherButton.setTitleColor(UIColor.whiteColor(), forState: .Focused)
view.addSubview(myOtherButton)
}
// Function to create a UIImage filled with a UIColor
func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRectMake(0, 0, 1, 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
This example in action:
