selected and deselected checkbox in Swift - swift

How to know my button selected or not in swift 3 .selected property not found.
when i type checkBtn.selected not found in Swift 3 (Xcode 8.0)
if let button = sender as? UIButton {
if button.selected {
// set selected
button.selected = true
} else {
// set deselected
button.selected = false
}
}

try this below code
if let button = sender as? UIButton {
if button.isSelected {
// set selected
button.isSelected = true
} else {
// set deselected
button.isSelected = false
}
}
For shorthand, try this
if let button = sender as? UIButton {
button.isSelected = !button.isSelected
}

In swift 3 you will have isSelected instead of selected. Your code looks fine just make a change.

if let button = sender as? UIButton {
if button.isSelected {
//for selected input
} else {
//for not selected input
}
button.isSelected = !button.isSelected //toggle the text box
}

#IBOutlet weak var btnCheckBox: UIButton!
#IBAction func btnCheckBoxClick(_ sender: UIButton) {
if btnCheckBox.isSelected {
btnCheckBox.isSelected = false
btnCheckBox.setImage(#imageLiteral(resourceName: "icon_checkbox_inactive"), for: .normal)
}else {
btnCheckBox.isSelected = true
btnCheckBox.setImage(#imageLiteral(resourceName: "icon_checkbox_active"), for: .normal)
}
}
It worked for me.

Related

Why doesn't my UILabel change when I press the button?

By pressing a button in my app, the value of a variable falls by 3. While this happens without any issues, the label which uses string interpolation to show that variable as its text (label.text) does not reflect the change.
How can I make it so pressing the button changes the value of the UILabel?
import UIKit
class ViewController: UIViewController {
var token = 5
let theButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("button", for: .normal)
button.backgroundColor = .systemPink
button.addTarget(self, action: #selector(theButtonPressed), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
#objc func theButtonPressed() {
if token >= 3 {
token -= 3
print("ok done")
} else {
print("nope")
}
}
lazy var tokenLabel: UILabel = {
let label = UILabel()
label.text = "\(token)"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBlue
view.addSubview(tokenLabel)
view.addSubview(theButton)
theButton.heightAnchor.constraint(equalToConstant: 100).isActive = true
theButton.widthAnchor.constraint(equalToConstant: 200).isActive = true
theButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
theButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
tokenLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 60).isActive = true
tokenLabel.heightAnchor.constraint(equalToConstant: 300).isActive = true
tokenLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
tokenLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
}
You need to update the label's text when the button is pressed.
#objc func theButtonPressed() {
if token >= 3 {
token -= 3
print("ok done")
tokenLabel.text = "\(token)" // <- update
} else {
print("nope")
}
}
Or, you can observe the property token and change the label when a new value is set.
var token = 5 {
didSet {
tokenLabel.text = "\(token)"
}
}
#objc func theButtonPressed() {
if token >= 3 {
token -= 3
print("ok done")
} else {
print("nope")
}
}

What conditional logic can be used for subclassed booleans in Swift?

I'm subclassing a UITextfield in order to create a overlay button to the right which will toggle the isSecureTextEntry boolean. Typically when creating IBActions in storyboard the boolean is determined based on the sender which I'd implement in Objective-C code like this:
-(IBAction)showPasswordTapped:(UIButton *)sender{
sender.selected = !sender.selected;
self.passwordField.secureTextEntry = !sender.selected;
}
However, now that I'm subclassing I was thinking of using an if else statement but the logic looked as if it would just set the boolean back to true. What would be the appropriate conditional statement if I don't have access to sender?
Here is my subclass in Swift:
class SecurePasswordUITextField : UITextField {
override func awakeFromNib() {
super.awakeFromNib()
self.isSecureTextEntry = true
var overlayButton = UIButton.init(type: UIButtonType.custom)
overlayButton.titleLabel = "Show"
overlayButton.addTarget(self, action: #selector(showSecureCharacters), for: .touchUpInside)
overlayButton = CGRect.init(x: self.bounds.origin.x, y: self.bounds.origin.y, width: 28, height: 28)
self.rightView = overlayButton
self.rightViewMode = UITextFieldViewMode.always
}
func showSecureCharacters(){
if self.isSecureTextEntry {
self.isSecureTextEntry = false
} else {
self.isSecureTextEntry = true
}
if !self.isSecureTextEntry{
self.isSecureTextEntry = true
} else {
self.isSecureTextEntry = false
}
}
}
You can access the sender
overlayButton.addTarget(self, action: #selector(showSecureCharacters(_:)), for: .touchUpInside)
//
#objc func showSecureCharacters(_ sender:UIButton){ --- }
Also this is sufficient
self.isSecureTextEntry = !self.isSecureTextEntry

check object type for UIButton

How can I verify the object type?
the goal is to check an object custom type to check the value
#IBAction func showAnswer(_ sender: UIButton) {
let question: Question = questions[currentQuestionIndex]
let rightAnswer = question.answers![question.answer]
let subViews = self.view.subviews
subViews.forEach { view in
if view.isMember(of: AnswerButton.self) {
let btn = view as! AnswerButton
if btn.titleLabel!.text == rightAnswer {
btn.hightlight()
}
}
}
}
this is the UI. the button with the right answer should highlight if this is the right answer.
enter image description here
Instead of
if view.isMember(of: AnswerButton.self) {
let btn = view as! AnswerButton
if btn.titleLabel!.text == rightAnswer {
btn.hightlight()
}
}
Use conditional downcasting:
if let btn = view as? AnswerButton {
// btn could be accessed as an instance of `AnswerButton` now
if btn.titleLabel!.text == rightAnswer {
btn.hightlight()
}
}
If you don't need to downcast the button then you can loop over the subviews with condition:
for view in subviews where view is AnswerButton {
// view is still treated as an instance of UIView but could be downcast to AnswerButton
}

swift - change label in header when UI Switch changes in the Navigation Bar

I want to change the label in my header to correlate with my UISwitch
though I have have no success as yet?
setLeftNavButton() is called in viewDidLoad()
func setLeftNavButton() {
let switchControl=UISwitch()
//switchControl.isOn = true
//switchControl.setOn(true, animated: false)
switchControl.addTarget(self, action: #selector(switchValueDidChange), for: .valueChanged)
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: switchControl)
self.switchControl = switchControl
}
var switchControl: UISwitch?
func switchValueDidChange(){
guard let mySwitch = switchControl else { return }
if mySwitch.isOn {
header?.onlineOfflineStatusLabel.text = "on"
}
else {
header?.onlineOfflineStatusLabel.text = "off"
}
self.header?.reloadInputViews()
self.collectionView?.reloadData()
}
try this:
func setLeftNavButton() {
let switchControl = UISwitch()
switchControl.addTarget(self, action: #selector(switchValueDidChange(_:)), for: .valueChanged)
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: switchControl)
self.switchControl = switchControl
}
#objc
func switchValueDidChange(_ sender: UISwitch){
if sender.isOn {
header?.onlineOfflineStatusLabel.text = "on"
} else {
header?.onlineOfflineStatusLabel.text = "off"
}
self.header?.reloadInputViews()
self.collectionView?.reloadData()
}

Swift - How To Save Image Button?

How to save On-Off value of a button? I have a On-Off button, when a user opens the app and click the Off button, I want the app to save it, so that when the app is reopened, the value of the button is still Off. Hopefully, this can be done by using User Defaults. My code:
class ViewController: UIViewController {
var soundEnable:Bool = true
var soundImage:UIImage?
#IBAction func soundbtn(_ sender: UIButton) {
let soundButton = sender
if (soundEnable) {
soundImage = UIImage.init(named: "mute.png")
soundEnable = false
} else {
soundImage = UIImage.init(named: "sound.png")
soundEnable = true
}
soundButton.setImage(soundImage, for: UIControlState.normal)
}
}
You need to set the image one more place at viewDidLoad.
You input the wrong parameter for setImage:
soundButton.setImage(soundImage, for: UIControlState())
it should be a specific state:
soundButton.setImage(soundImage, for: UIControlState.normal)
Please write these lines in viewDidLoad method
override func viewDidLoad() {
super.viewDidLoad()
if (UserDefaultsManager.useDarkTheme) {
soundImage = UIImage.init(named: "mute")
print(UserDefaultsManager.useDarkTheme)
} else {
soundImage = UIImage.init(named: "sound")
print(UserDefaultsManager.useDarkTheme)
}
}
#IBOutlet weak var backgroundImage: UIImageView!
let ImageNameKey = "ImageNameKey"
let soundbg = UIImage(named: "sound")
let mutebg = UIImage(named: "mute")
override func viewDidLoad() {
super.viewDidLoad()
//Sound.play(file: "bg", fileExtension: "wav", numberOfLoops: -1)
let defaults = UserDefaults.standard
if let name = defaults.string(forKey: ImageNameKey) {
if (name == "sound") {
backgroundImage.image = soundbg
} else {
backgroundImage.image = mutebg
}
}
}
#IBAction func clickbtn(_ sender: UIButton) {
let defaults = UserDefaults.standard
if(backgroundImage.image == soundbg){
backgroundImage.image = mutebg
defaults.set("mute", forKey: ImageNameKey)
Sound.enabled = false
}
else{
backgroundImage.image = soundbg
defaults.set("sound", forKey: ImageNameKey)
Sound.enabled = true
}
}