Extension vs Subclass. How to explain different behavior when I set background color for UIButton - swift

I want to change background color for UIButton in highlighted state.
I use two different ways.
Case #1 with extension:
extension UIButton {
override open func awakeFromNib() {
super.awakeFromNib()
backgroundColor = .green
setTitleColor(.white, for: .normal)
}
override open var isHighlighted :Bool {
didSet{
if isHighlighted {
backgroundColor = .red
} else {
backgroundColor = .green
}
}
}
}
Case #2 with subclass:
class SHButton: UIButton {
override open func awakeFromNib() {
super.awakeFromNib()
backgroundColor = .green
setTitleColor(.white, for: .normal)
}
override open var isHighlighted :Bool {
didSet{
if isHighlighted {
backgroundColor = .red
} else {
backgroundColor = .green
}
}
}
}
I use very similar code, but I see different results in runtime.
In second case button title has not a white color.
Why we can see so different results in runtime?
Updated. This question has been resolved. I'm dummy. I forgot to change button Type to Custom. When I have did it both examples began to work identically.

this should also fix your problem
button.setTitleColor(.white, for: .highlighted)

Related

How do I make my textField border change to a different color every-time it is selected?

I've created a custom textField class that I'm using throughout my app, but I want to know how I can change the border color to red every-time a field is selected without having to implement a delegate on each view controller that the textField shows up on.
Is there a way to override a standard function when I'm creating my textField subclass? For buttons, I had success using the following code, but isHighlighted doesn't work for textFields and it doesn't look like I can override isEditing:
override var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? .red : .blue
}
}
In your UITextField subclass, you can override becomeFirstResponder and resignFirstResponder and perform your changes there:
class YourTextFieldSubclass: UITextField {
override func becomeFirstResponder() -> Bool {
let didBecomeFirstResponder = super.becomeFirstResponder()
if didBecomeFirstResponder {
layer.borderColor = UIColor.red.cgColor
layer.borderWidth = 2
layer.cornerRadius = 5
}
return didBecomeFirstResponder
}
override func resignFirstResponder() -> Bool {
let didResignFirstResponder = super.resignFirstResponder()
if didResignFirstResponder {
layer.borderColor = UIColor.clear.cgColor
layer.borderWidth = 0
layer.cornerRadius = 0
}
return didResignFirstResponder
}
}
Make sure to call super and return that value for both of these overridden methods as in the above example.

UITextField clear button color Swift

How can I change clear button color or background color in UITextField. I tried get subviews of textField, but in subviews not clear button.
import UIKit
class CustomTextField: UITextField {
override func layoutSubviews() {
super.layoutSubviews()
for view in subviews {
if let button = view as? UIButton {
button.setImage(button.image(for: .normal)?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
}
}
}
}

All objects disappear in view controller (main storyboard) when I use custom #IBDesignable UITextfield class. (Xcode 10, Swift 4.2)

All objects disappear in view controller (main storyboard) when I use custom #IBDesignable UITextfield class. Main storyboard looks like this:
(Xcode 10, Swift 4.2)
As you see, it shows an error also. But Xcode shows 'Build Succeeded' when I run the app.
I use custom #IBDesignable UITextfield class like this below:
import UIKit
import AKMaskField
#IBDesignable
class MyTextFieldStyle: AKMaskField {
#IBInspectable var secureEntry : Bool = false
#IBInspectable var myBorderColor : UIColor = UIColor.white {
didSet {
self.layer.borderColor = myBorderColor.cgColor
}
}
#objc func secureButtonPressed (sender: UIButton) {
self.secureEntry = !self.secureEntry
self.isSecureTextEntry = self.secureEntry
}
override func awakeFromNib() {
super.awakeFromNib()
if self.secureEntry {
let btn = UIButton(type: .custom)
btn.setImage(#imageLiteral(resourceName: "eye-17-glyph-16"), for: .normal)
btn.addTarget(self, action: #selector(self.secureButtonPressed(sender:)), for: .touchUpInside)
btn.sizeToFit()
btn.frame = CGRect(x: self.frame.size.width-(btn.frame.size.width+5), y: (self.frame.size.height-btn.frame.size.height)/2, width: btn.frame.size.width, height: btn.frame.size.height)
self.addSubview(btn)
}
self.layer.borderColor = self.myBorderColor.cgColor
}
}
It becomes fine when I close and open Xcode. It looks like a bug. This was working fine.

Swift UIButton not appearing on screen

I have a view in my tabbar controller where I would like to show a button. I create this button programmatically based of a condition, therefore I use the following code but nothing is appearing:
override func viewDidLoad() {
super.viewDidLoad()
if !Settings.getIsConnected() {
notConnected()
}
}
func notConnected() {
let connectBtn = UIButton(frame: CGRect(x: self.view.center.x, y: self.view.center.y, width: 200, height: 45))
connectBtn.setTitle("Connect", forState: .Normal)
connectBtn.addTarget(self, action:#selector(self.pressedConnect(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(connectBtn)
print("Button created")
}
func pressedConnect(sender: UIButton!) {
}
I am clueless on what I am doing wrong. Anyone got suggestions? Cause it does print out "Button created" so it definitely runs the code inside the noConnected() method.
Add a background color to your UIButton and add a tint color to the title. This will resolve the problem
Try moving the code to viewDidAppear and see if the button is showing up.
The frame is not correctly set when in viewDidLoad. Use the method viewDidLayoutSubviews for the earliest possible time where the frame is correctly setup for a ViewController.
With this code change, you will need some additional logic for when your button should be added as a subview though.
A programmatically created button may not show up because of more reasons, e.g:
the tint color is not set
the background color is not set
the button is not added to the view hierarchy
the button is hidden
In your case, you should change the tint color or the background color of your button.
E.g.:
Swift 4.2:
private lazy var connectButton: UIButton = {
let button = UIButton(type: .custom)
button.backgroundColor = .green
button.setTitleColor(.black, for: .normal)
button.setTitle(NSLocalizedString("Connect", comment: ""), for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(connectButton)
}
You can re-check the button properties in the storyboard that it is not hidden.

swift Button display

I create a button from my code.
How can I write code to let button change to like Default?
Am I missing some code?
I have tried adjustsImageWhenHighlighted or something ....
I mean when I push Button ..the button will become to transparent(I still push on) and when i push off will become back ...
like down below two images...
import UIKit
class ViewController: UIViewController {
var testButton:UIButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.whiteColor()
testButton.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
testButton.backgroundColor = UIColor.whiteColor()
testButton.setTitle("123", forState:.Normal)
testButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
testButton.tag = 1
testButton.addTarget(self, action: #selector(number), forControlEvents: .TouchUpInside)
self.view.addSubview(testButton)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func number(){
print("\("100")")
}
}
You could either add:
testButton.setTitleColor(UIColor.redColor(), forState: .Highlighted)
or have the colour applied in the button's function:
#IBAction func testButton(sender: UIButton) {
testButton.titleLabel.textColor = UIColor.redColor()
}
I've used redColor here for the examples, but you could change that to whatever colour you want to create the desired effect. I've not actually compiled this, so apologies if you need to correct any of the syntax to get it to work.