Select/deselect buttons swift xcode 7 - ios

Part way done with learning swift but I hit a small wall and yet again, I'm sure I'm just a bit new at this and an easy solution is there but I'm having trouble figuring out how to select/deselect buttons below is what I have so far and it is a button turns into a checkmark when clicked on... I've gotten that far but I need that button to deselect when clicked on again and then obviously be able to be clicked again if need be.
#IBAction func buttonPressed(sender: AnyObject) {
sender.setImage(UIImage(named: "Checkmark.png"), forState: .Normal)
}

Swift 3 note: .selected and .checked are now lower case UIControlState values in the SDK, and some of the methods have been renamed:
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), for: .normal)
button.setImage(UIImage(named: "Checked"), for: .selected)
You can also now use image literals with Xcode 8 instead of UIImage(named:):
#imageLiteral(resourceName: "Unchecked")
Swift 2:
Why not use the .Selected state of the button as the "checked" state, and the .Normal state as the "unchecked" state.
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), forState: .Normal)
button.setImage(UIImage(named: "Checked"), forState: .Selected)
// ...
#IBAction func buttonPressed(sender: AnyObject) {
if let button = sender as? UIButton {
if button.selected {
// set deselected
button.selected = false
} else {
// set selected
button.selected = true
}
}
}

You dont need to set selected in condition. I just doing with following method in swift:
func selectDeselect(sender: UIButton){
sender.selected = !sender.selected
if(sender.selected == true)
{
sender.setImage(UIImage(named:"select_heart"), forState: UIControlState.Normal)
}
else
{
sender.setImage(UIImage(named:"heart"), forState: UIControlState.Normal)
}
}

Here is Working code for swift 4.
Make Sure you need to connect Button IBAction Outlet as UIButton and set default button image from storyboard whatever you want.
#IBAction func btnTapped(_ sender: UIButton) {
if sender.currentImage == UIImage(named: "radio_unchecked"){
sender.setImage(UIImage(named: "radio_checked"), for: .normal)
}else{
sender.setImage(UIImage(named: "radio_unchecked"), for: .normal)
}
}

update for Swift 4+ :
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), forState: .Normal)
button.setImage(UIImage(named: "Checked"), forState: .Selected)
#IBAction func buttonPressed(sender: AnyObject) {
if let button = sender {
if button.isSelected {
// set deselected
button.isSelected = false
} else {
// set selected
button.isSelected = true
}
}
}

Set uncheck image on default state from storyboard and check image on selected state from storyboard.
#IBAction func buttonPressed(sender: AnyObject) {
buttonOutlet.isSelected = !buttonOutlet.isSelected
}

private(set) lazy var myButton: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), for: .normal)
button.setImage(UIImage(named: "Checked"), for: .selected)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
#objc
func buttonTapped(sender: AnyObject) {
sender.isSelected.toggle()
}

To select only the pressed button out of three buttons and deselect the others when designated button is pressed.
#IBAction func buttonPressed(_ sender: UIButton) {
// Deselect all buttons
button1.isSelected = false
button2.isSelected = false
button3.isSelected = false
// Select the pressed button
sender.isSelected = true
}

Related

Swift create custom logic for radio button

I have four custom UIButton, I applied button image radio (checked and checked). four button I have separate action method I can change the Image easily but if I checked first button another three button need uncheck. it should react like radio button.
Here, below my code
#IBAction func first_scheme(_ sender: Any) {
bRec = !bRec
if (bRec == true) {
firstscheme_button.setImage(UIImage(named: "uncheck.png"), for: .normal)
} else {
firstscheme_button.setImage(UIImage(named: "check.png"), for: .normal)
}
}
If you have 4 radio buttons at all times, you can put them in an array.
var radioButtons: [ButtonType] = [r1, r2, r3, r4]
You can now access the button in a loop and set the values for the other button to 'unchecked'.
func setRadioButtons(button: ButtonType) {
for radioButton in radioButtons {
if radioButton !== button {
radioButton.setImage(UIImage(named: "uncheck.png"), for: .normal)
}
}
}
#IBAction func first_scheme(_ sender: Any) {
bRec = !bRec
if bRec {
firstscheme_button.setImage(UIImage(named: "uncheck.png"), for: .normal)
} else {
firstscheme_button.setImage(UIImage(named: "check.png"), for: .normal)
}
setRadioButtons(button: sender)
}
alternate method
If all you want to do is check the button clicked and uncheck the other buttons, the logic is simpler.
Create the common action for all radio buttons as well create the IBOutletcollection for your all UIButtons ,
var radioButtons: [UIButton] = [r1, r2, r3, r4]
finally execute the common method as
func setRadioButtons(button: UIButton) {
for getradioButton in radioButtons {
getradioButton.setImage(UIImage(named: "uncheck.png"), for: .normal)
}
button.setImage(UIImage(named: "check.png"), for: .normal)
}
I suggest you set tags on the buttons with the simple tag property, and then you save it from a generic listener.
//first button selected
var lastTag = 0
#IBAction func first_scheme(_ sender: UIButton) {
buttonArray[lastTag].setImage(UIImage(named: "uncheck.png"), for: .normal)
lastTag = sender.tag
sender.setImage(UIImage(named: "check.png"), for: .normal)
}
You Can override isSelected variable in the custom UIButton and set the image depend on the isSelected value.
class customButton: UIButton {
override var isSelected: Bool {
willSet {
self.setImage(UIImage.init(named: "checked"), for: .normal)
}
didSet {
self.setImage(UIImage.init(named: "unchecked"), for: .normal)
}
}
}
After making 4 IBOutlets and 4 IBActions for the four custom UIButtons. you can easily select and unselect the buttons and apply your custom behaviour.
#IBAction func firstButtonAction(_ sender: Any) {
if let button = sender as? customButton {
button.isSelected = !button.isSelected
}
secondButton.isSelected = false
thirdButton.isSelected = false
fourthButton.isSelected = false
}

I want to change UIButton Image when tapped on it

I have 2 buttons in header on CollectionViewController. When i tap on one of them i'm changing an image of this buttons using UIControlState -> .normal .selected.
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
engSwitchButton.setImage(#imageLiteral(resourceName: "abc"), for: .normal)
geoSwitchButton.setImage(#imageLiteral(resourceName: "abg"), for: .normal)
engSwitchButton.setImage(#imageLiteral(resourceName: "abc2"),for: UIControlState.selected)
geoSwitchButton.setImage(#imageLiteral(resourceName: "abg2"), for: UIControlState.selected)
engSwitchButton.tag = Language.english.rawInt
geoSwitchButton.tag = Language.georgian.rawInt
}
#IBAction func languageSwitchTapped(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
selectedLanguage = Language(rawInt: sender.tag)!
collectionView.reloadData()
}
I want the button which i tapped first, get back to .normal state when i'm changing state of 2d button with tapping on it.
To change a button image on tap you should use the UIControlState.highlighted.
So change:
engSwitchButton.setImage(#imageLiteral(resourceName: "abc2"),for: UIControlState.selected)
geoSwitchButton.setImage(#imageLiteral(resourceName: "abg2"), for: UIControlState.selected)
To this:
engSwitchButton.setImage(#imageLiteral(resourceName: "abc2"),for: UIControlState.highlighted)
geoSwitchButton.setImage(#imageLiteral(resourceName: "abg2"), for: UIControlState.highlighted)
#IBAction func yourFirstButton(_ sender: Any) {
firstButton.setImage(UIImage(named: "yourButtonPressedImage")!, for: .normal)
secondbutton.setImage(UIImage(named: "yourNormalImage")!, for: .normal)
}
and in your second buttons #IBAction method just switch the images for the buttons
#IBAction func yourSecondButton(_ sender: Any) {
secondButton.setImage(UIImage(named: "yourButtonPressedImage")!, for: .normal)
firsBbutton.setImage(UIImage(named: "yourNormalImage")!, for: .normal)
}

Toggle between select/deselect UIButton

I have a button which I want to change background color and text when tapped(select) and bring it back to its original state when tapped again (deselect). I am able to select it but I am not being able to deselect it. I have researched on SO and I am getting errors in this code in the if-else part
#IBAction func btn1Pressed(_ sender: AnyObject) {
sender.setTitleColor(UIColor.blue, for: UIControlState.normal)
(sender as! UIButton).backgroundColor = UIColor.green
if sender.isSelected {
sender.selected = false
}
else {
sender.selected = true
}
}
Try this:
#IBAction func btnPressed(_ sender: AnyObject) {
guard let button = sender as? UIButton else { return }
if !button.isSelected {
button.isSelected = true
button.setTitleColor(UIColor.blue, for: UIControl.State.normal)
button.backgroundColor = UIColor.green
}
else {
button.isSelected = false
button.setTitleColor(UIColor.green, for: UIControl.State.normal)
button.backgroundColor = UIColor.blue
}
}
It sounds to me like UISwitch is what you're looking for. Give it a try instead of wasting time implementing something that's already there for you.
try this
#IBAction func btn1Pressed(sender: UIButton) {
if sender.selected {
sender.selected = false
sender.setTitleColor(UIColor.redColor(), forState: .Normal)
sender.backgroundColor = UIColor.blackColor()
}
else {
sender.selected = true
sender.setTitleColor(UIColor.redColor(), forState: .Selected)
sender.backgroundColor = UIColor.blackColor()
}
}
Change background color of selected button from storyboard like below in state config choose selected and then change background color and also coustomize default for normal button.
and use below in action
(sender as! UIButton).selected = !(sender as! UIButton).selected
Please try this code first you need to crate action and propert of the button like
#IBOutlet var btn_ButtonPressed: UIButton!
then Action.
#IBAction func click_ButtonPressed(_ sender: Any) {
if !sender.isSelected() {
sender.selected = true
btn_ButtonPressed.setTitleColor(UIColor.red, forState: .normal)
btn_ButtonPressed.backgroundColor = UIColor.yellow
}
else {
sender.selected = false
btn_ButtonPressed.setTitleColor(UIColor.yellow, forState: .normal)
btn_ButtonPressed.backgroundColor = UIColor.red
}
}
this one worked fine for me!
//
#IBAction func buttonColorChanger(sender : UIButton ) {
if button.isSelected == false
{
button.backgroundColor = UIColor.purple
print("selected")
button.setTitle("selected", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.isSelected = true
}else{
button.backgroundColor = UIColor.white
print("unselected")
button.isSelected = false
}
}
A cleaner approach would be:
#objc private func buttonTapped(_ sender: UIButton) {
sender.isSelected.toggle()
if selected {
// Setup appearance for selected state.
} else {
// Setup appearance for deselected state.
}
}

UIButton text returns to original value after setting a new value to it

My UIButton is in a UICollectionviewcell, which is in a UICollectionview, which is in a UITableViewCell, which is in a UITableView.
The button is a like button, I want it to change its text when clicked. But after changing the text, it returns the original value. What might be the reason here?
Here is what it looks like:
https://gfycat.com/UnlawfulGroundedErin
This is the onClickEvent of button:
#IBAction func actionClick(sender: MyActionButton) {
if (sender.toggle){
print("Do dislike call here.")
sender.toggle = false
sender.titleLabel?.text = "Like"
}else{
print("Do like call here.")
sender.toggle = true
sender.titleLabel?.text = "Unlike"
}
}
Try This. It will work properly
#IBAction func actionClick(sender: MyActionButton) {
if (sender.toggle){
print("Do dislike call here.")
sender.toggle = false
sender.titleLabel?.text = "Like"
sender.setTitle("Like", forState: UIControlState.Normal)
}else{
print("Do like call here.")
sender.toggle = true
sender.setTitle("Unlike", forState: UIControlState.Normal)
}
}
UIButton have different texts for its title in different states.
Just for your knowledge
In viewDidLoad:
btnObject.setTitle("Like", forState: UIControlState.Normal)
btnObject.setTitle("Unlike", forState: UIControlState.Selected)
then in method actionClick: if you write only one statement,
sender.selected = !sender.selected;
it will work.
try this
#IBAction func actionClick(sender: UIButton) {
if sender.isSelected() {
sender.selected = false
sender.setTitle("Like", forState: UIControlState.Normal)
}
else {
sender.selected = true
sender.setTitle("Unlike", forState: UIControlState.Normal)
}
}
Choice-2
var isSelectFirst:Bool = false
#IBAction func actionClick(sender: UIButton) {
if isHighLighted == false{
sender.setTitle("Unlike", forState: UIControlState.Normal)
isHighLighted = true
}else{
sender.setTitle("Like", forState: UIControlState.Normal)
isHighLighted = false
}
}

How to change button repeatedly when tapped?

Using Swift, how do I make a:
Button with words "start", that changes to "pause" and vice versa when tapped? Not just once, but can be done infinitely? (e.g. in a stopwatch app)
Custom image button that changes between 2 image when tapped, that can also be done (tapped & change) infinitely?
Step 1: Create a Bool variable
var isPlaying:Bool = false
Step 2: Connect your button with this IBAction method:
#IBAction func btnStartStop(sender: UIButton) {
if isPlaying{
isPlaying = false
sender.setTitle("Pause", forState: UIControlState.Normal)
sender.setImage(pauseImage, forState: .Normal)
//Pause Stopwatch
}
else{
isPlaying = true
sender.setTitle("Play", forState: UIControlState.Normal)
sender.setImage(playImage, forState: .Normal)
//Play Stopwatch
}
}
In your storyboard, set the Default state title to "Start" and the Selected state title to "Pause"
Or alternatively, if you're doing it in code:
startPauseButton.setTitle("Start", forState: .Normal)
startPauseButton.setTitle("Pause", forState: .Selected)
In your IBAction func, toggle the button.selected property between true & false
#IBAction func toggleStopwatch(button:UIButton) {
if button.selected {
// Pause the stopwatch
} else {
// Start the stopwatch
}
button.selected = !button.selected
}
You can also set different images for different states: Default, Highlighted, Selected, Disabled
In the #IBAction of the button (assuming you are using storyboards), you change the title or image of the button to what you want. You can also check for the title or image and perform an action based on what you have.
#IBAction func pressbutton(sender: UIButton) {
switch sender.titleLabel?.text {
case "Play":
play()
case "Pause":
pause()
default:
other()
}
sender.titleLabel?.text = "Whatever you want"
}
Or with images (assuming you have an images array somewhere that stores the images, which you should):
#IBAction func pressbutton(sender: UIButton) {
switch sender.imageView!.image! {
case images[0]:
play()
case images[1]:
pause()
default:
other()
}
sender.imageView?.image = UIImage(...)
}
Try this....
#IBAction func btnStopWatch(sender: UIButton) {
if btnStopWatch.selected == true {
btnStopWatch.setTitle("stop", forState: UIControlState.Normal)
btnStopWatch.setImage(stopImage, forState: UIControlState.Normal)
btnStopWatch.selected = false
} else {
btnStopWatch.setTitle("start", forState: UIControlState.Normal)
btnStopWatch.setImage(startImage, forState: UIControlState.Normal)
btnStopWatch.selected = true
}
}
#1. Toggle a UIButton title
With Swift 3, UIButton has a method called setTitle(_:for:). setTitle(_:for:) has the following declaration:
func setTitle(_ title: String?, for state: UIControlState)
Sets the title to use for the specified state.
The following Playground code shows how to use setTitle(_:for:) in order to toggle the title of a button according to its state:
import PlaygroundSupport
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let button = UIButton(type: UIButtonType.system)
button.addTarget(self, action: #selector(toggle(sender:)), for: UIControlEvents.touchUpInside)
// Set button's states
button.setTitle("Start", for: UIControlState.normal)
button.setTitle("Pause", for: UIControlState.selected)
// set layout
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = button.centerXAnchor.constraint(equalTo: view.centerXAnchor)
let verticalConstraint = button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint])
}
/// trigger action when button is tapped
func toggle(sender: UIButton) {
sender.isSelected = !sender.isSelected
print("Button state: \(sender.isSelected)")
}
}
let vc = ViewController()
PlaygroundPage.current.liveView = vc
Preview your view controller in the Playground assistant editor using View > Assistant Editor > Show Assistant Editor
#2. Toggle a UIButton image
UIButton has a method called setImage(_:for:). setImage(_:for:) has the following declaration:
func setImage(_ image: UIImage?, for state: UIControlState)
Sets the image to use for the specified state.
The following Playground code shows how to use setImage(_:for:) in order to toggle the title of a button according to its state:
import PlaygroundSupport
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let button = UIButton()
button.addTarget(self, action: #selector(toggle(sender:)), for: UIControlEvents.touchUpInside)
// Set button's states
button.setImage(UIImage(named: "on.png"), for: UIControlState.normal)
button.setImage(UIImage(named: "off.png"), for: UIControlState.selected)
// set layout
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = button.centerXAnchor.constraint(equalTo: view.centerXAnchor)
let verticalConstraint = button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
let heightConstraint = button.heightAnchor.constraint(equalToConstant: 100)
let widthConstraint = button.widthAnchor.constraint(equalToConstant: 100)
NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, heightConstraint, widthConstraint])
}
/// trigger action when button is tapped
func toggle(sender: UIButton) {
sender.isSelected = !sender.isSelected
print("Button state: \(sender.isSelected)")
}
}
let vc = ViewController()
PlaygroundPage.current.liveView = vc
Preview your view controller in the Playground assistant editor using View > Assistant Editor > Show Assistant Editor

Resources