How to make dynamically changing text in a button in swift? - ios

When user taps "download" button i need to change the title of a button to
"loading..." but the number of dots must dynamically change from 1 to 3. How can i make it for certain amount of time(5-10 sec) ? Or do i just need to setTitle multiple times ?
button.setTitle("loading.", forState: .Normal)

You need to use
button.setTitle("loading.", forState: .Normal)
button.setTitle("loading..", forState: .Normal)
button.setTitle("loading...", forState: .Normal)
whenever you want to change the number of dots.
Call one of the above after a delay or whenever you need to update the button.
EDIT: To prevent your button's title from blinking (as pointed out by teamnorge) use:
UIView.performWithoutAnimation {
button.setTitle("loading...", forState: .Normal)
}

#IBAction func renameClassButton(sender: AnyObject) {
classTopButton.text = "\(classTopTextField)"
}

You can d it this way:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var loading: UIButton!
//Create an array for your button name
let buttonNameArray = ["loading.","loading..","loading..."]
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func loadingButton(sender: AnyObject) {
//Set delay time for changing name
var delayTime = 1.0
for name in buttonNameArray {
self.delay(delayTime++){
self.loading.setTitle(name, forState: .Normal)
}
}
}
//Function for delay
func delay(delay:Double, closure:()->()) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(delay * Double(NSEC_PER_SEC))),dispatch_get_main_queue(), closure)
}
}
And your result will be:
Hope this will help.

button.setTitle("my text here", forState: .Normal)

Related

Select/deselect buttons swift xcode 7

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
}

UIButton text not staying changing

I am developing a simple iPhone app in Swift
I have a customUITableViewCell. In the cell I have a normal UIButton with text of "Hello World".
In my code for the custom cell, I have the following function:
#IBAction func buttonAction(sender: AnyObject) {
if likeButton.titleLabel?.text == "Hello World" {
likeButton.titleLabel?.text = "Hi!"
}
}
When I tap theUIButton, the text of theUIButton changes to "Hi!" for just a split second! And then it quickly changes back to "Hello World"...is there any way to fix that?
Why is it doing that?
Use UIButtons's setTitle: forState: rather than setting text on titleLabel of button. For Instance-
Initial set up
likeButton.setTitle("Hello World", forState: UIControlState.Normal)
On click set up-
#IBAction func buttonAction(sender: AnyObject) {
if likeButton.titleLabel?.text == "Hello World" {
likeButton.setTitle("Hi!", forState: UIControlState.Normal)
}
}
likeButton.setTitle("my text here", forState: UIControlState.Normal)
Use this code
Do Something like this :
#IBAction func buttonAction(sender: AnyObject) {
likeButton.setTitle("Hi!", forState: UIControlState.Normal)
}
it works here, hope also work there, set your default value-
yourButton.setTitle("Hello", forState: UIControlState.Normal)
when you tapped your button set this
#IBAction func buttonAction(sender: AnyObject) {
if yourButton.titleLabel?.text == "Hello " {
yourButton.setTitle("Max", forState: UIControlState.Normal)
}
}

Trying to understand button behaviour

this is my first project, and i try to set a button title for some time and after it should reset.
This my code:
The first (test) snippet simply tries to set immediately to "tapped" and then after 2 secs to reset to "tap me".
What i see is disappering the button for 2sec and then only "tap me" again!?
#IBOutlet weak var button1: UIButton!
#IBAction func button1Tapped(sender: UIButton) {
sender.setTitle("tapped", forState: .Highlighted)
NSThread.sleepForTimeInterval(2.0)
sender.setTitle("tap me", forState: .Normal)
}
The second example is more what i really want!
But for some reason I immediately fail here, because the alert simply does not show up!?
Any hints?
#IBOutlet weak var button2: UIButton!
#IBAction func button2Tapped(sender: AnyObject) {
}
func isOK(sender:UIAlertAction!){
button2.setTitle("tapped", forState: .Normal)
NSThread.sleepForTimeInterval(2.0)
button2.setTitle("tap me", forState: .Normal)
}
func isCancel(sender:UIAlertAction!){
}
#IBAction func button2Tapped(sender: UIButton) {
let alert = UIAlertController(title: "Test", message: "button", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title:"OK", style: UIAlertActionStyle.Default, handler: isOK))
alert.addAction(UIAlertAction(title:"Cancel", style: UIAlertActionStyle.Cancel, handler: isCancel))
self.presentViewController(alert, animated: true, completion: nil)
}
OK,
i changed to this:
#IBOutlet weak var button1: UIButton!
#IBAction func button1Tapped(sender: UIButton) {
sender.selected = true
NSThread.sleepForTimeInterval(2.0)
sender.selected = false
}
override func viewDidLoad() {
super.viewDidLoad()
button1.setTitle("tapped", forState: .Selected)
button1.setTitle("tap me", forState: .Normal)
}
but it shows the same behaviour.
Actually it shows "tapped" but only when i keep pressing!?
Firstly, delete all the code you have written. Instead, use this code that I have taken from answer of Matt. Credits goes to him. This function is needed to "delay" the action of something.
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
Now create an #IBAction connection:
#IBAction func button(sender: AnyObject) {
// Okay, the button has been tapped
button.setTitle("tapped", forState: .Normal)
// after two seconds...
delay(2.0) {
// change the button's title:
button.setTitle("tap here!", forState: .Normal)
}
}
One of the problems with the first way that you attempted is that you have simply set the title for two different states of sender: .Highlighted and .Normal. If you never change the state of sender, you'll only ever see the title associated with its current state (.Normal by default).
You could update the title for the same state twice to get the behaviour you want, or you might consider using the .Selected state of the button, depending on your application's implementation and usage of the button.
// Call these two setTitle lines wherever you are instantiating your button
// or otherwise setting up your view:
sender.setTitle("tapped", forState: .Selected)
sender.setTitle("tap me", forState: .Normal)
// Somewhere else, you can call either of these:
sender.selected = YES // sender now shows "tapped"
sender.selected = NO // sender now shows "tap me"
Secondly, we need to address your threading issues.
At some point, the main thread has been scheduled to run the code contained within your isOK method. It also has work scheduled to update the UI. Your main thread's queue might look something like this:
(0): __ execute isOK(..)
(1): __ do some other stuff
(2): __ update the UI
(3): __ do some other stuff
If you update your UI in (0) and then update it again in (0), the first update won't be seen because the queue hasn't been allowed to progress to (2) in between. When you NSThread.sleepForTimeInterval() in (0), you are delaying UI updates and freezing your app.
Instead, you'll want to put your sleep into a different queue and then inject your following commands back onto the main thread after your duration has elapsed.
You can do this in a few ways, but the easiest way is to use GCD (Grand Central Dispatch) and dispatch_after.
#IBAction func button1Tapped(sender: UIButton) {
sender.selected = YES
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC))),
dispatch_get_main_queue(), ^{
sender.selected = NO
});
}

Changing image of UIButton when touched

I'm changing the image of my button by using a boolean like this, but I have a couple of problems:
#IBOutlet weak var checkedButtonOutl: UIButton!
var hasBeenTouched = false
override func viewDidLoad() {
super.viewDidLoad()
checkedButtonOutl.setImage(uncheckedImage, forState: UIControlState.Normal)
checkedButtonOutl.addTarget(self, action: "click", forControlEvents: UIControlEvents.TouchUpInside)
checkedButtonOutl.showsTouchWhenHighlighted = false
}
func click(){
if hasBeenTouched == false{
checkedButtonOutl.setImage(uncheckedImage, forState: UIControlState.Normal)
hasBeenTouched = true
}else{
checkedButtonOutl.setImage(checkedImage, forState: UIControlState.Normal)
hasBeenTouched = false
Right after the view has loaded, you have to touch the button two times before it changes. Also, when the button is touched it highlights, which I don't want and I thought the showsTouchWhenHighlighted function would take care of.
Any suggestions on how to fix these two problems would be appreciated.

Swift if statement being re-executed when button title updated

So I have this very simple code, the button is set to the title "Title1" in IB
#IBAction func changeTitle(sender: AnyObject) {
let button = sender as UIButton
if (button.titleLabel == "Title1") {
button.setTitle("Title2", forState: .Normal)
} else {
button.setTitle("Title1", forState: .Normal)
}
}
So what's happening is that the first condition in the if statement gets executed, then the line of code updating the title of the button is hit, where then it goes back to the if statement, then finding it false, and skipping to the else {} now... I cannot figure out why this is happening.
Thanks in advance
This should work:
#IBAction func changeTitle(sender: AnyObject) {
let button = sender as UIButton
if (button.titleLabel?.text == "Title1") {
button.setTitle("Title2", forState: .Normal)
} else {
button.setTitle("Title1", forState: .Normal)
}
}

Resources