segue text on button with action (swift3) - ios

I would like the user to hit the button add 1. Which then will display in the middle of the green box. So the user hits a button and the number one is displayed in the middle of the green box. This is not a counter so its just one. Think of it as a score card. The green box is referenced as score display.
import UIKit
class ViewController: UIViewController {
#IBOutlet var scoreDisplay: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func add1(_ sender: Any) {
}}

If I understood correctly, you wish to hide and show some views depending upon some user behaviour.
As of Swift 3, please take a look at the isHidden property of any UIView. You must have some #IBOutlets for your buttons, not only #IBActions.
A possible solution for you (write this in your add1 function):
scoreDisplay.setTitle("1", for: .normal)
scoreDisplay.isHidden = false
Of course, do not forget to firstly set the scoreDisplay as hidden in the Interface Builder.

Related

Swift UIbutton is clicked add a string and when clicked again it removes it

I'm a beginner in swift, I'm making an app in storyboard UIKit, and I need some help basically I need to set up a view controller that has buttons on it that when clicked add a string on the bottom of the VC, and if clicked again it will remove that same string. On the VC there going to be multiple buttons like this for options also on the bottom of the VC I need the label to update during the app also it should display like this for example. "Football","Basketball","Golf". It needs to be displayed just like that on the bottom with quotes and commas. I've to turn to make action buttons with a global array and put that inside each button but I can't figure out how to remove it when the button clicked again, also if you click the button again it'll add the same thing again so in the array you'll have two of the same strings. Anything would help.
P.S I need to do this in UIkit and Storyboard
You can make list of outlets to an array UIButton, handle list of actions when click into UIButton with a function. Using 'isSelected' property of UIButton to distinguish 'delete' or not.
class ViewController: UIViewController {
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet var allButtons: [UIButton]!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func didTapButton(_ sender: UIButton) {
sender.isSelected.toggle()
_updateDescription()
}
private
func _updateDescription() {
descriptionLabel.text = allButtons
.filter { $0.isSelected }
.compactMap { $0.titleLabel?.text }
.map { "\"\($0)\"" }
.joined(separator: ", ")
}
}

How to change background color in iOS/XCode on click

I'm trying to learn iOS programming. To start I want to change the background color of my view when a button is clicked. My entire code looks as follows, but when I click the button no change happens. I'm using Xcode 13.1. Also I'm using a storyboard.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var myBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
NSLog("The app has launched")
}
#IBAction func changeColorClicked(_ sender: UIButton) {
self.myBtn.backgroundColor=UIColor.green
NSLog("I want to change color to green")
}
}
I see the NSLog message when I click, just no color change.
Check a few things:
First make sure your IBOutlet and IBAction are connected to the button itself.
You don't need to declare self here as the button as its already declared above and you don't need to call an instance of the view controller you're using to access the button.
You can also declare it like this to change the colour of the button in the function:
myBtn.backgroundColor = .green
To change the button's background colour when pressed.
Update on this thread if you can get it working.

How do I set the color chosen by user as a background color for the entire IOS App?

I want the user to choose the preferred color by clicking the wanted button, and based on the choice it will be the background color of all pages in the App.
The code given is what I have used to change the background color through code, as shown in the image attached Screenshot of page sample . However, it changes temporary only and does not get saved when I move to another page and get back.
class ColorViewController: UIViewController {
#IBOutlet weak var redBtn: UIButton!
#IBOutlet weak var blueBtn: UIButton!
#IBAction func changeToRed(_ sender: UIButton) {
self.view.backgroundColor = UIColor.green
}
#IBAction func changeToBlue(_ sender: UIButton) {
self.view.backgroundColor = UIColor.cyan
}
If you also know how to save this color for a registered user (So every time the user signs in, the chosen background stays as is instead of reseting to default) it would be great. Please advise if you know the solution, I am new on Swift.
For saving user's color choice, you can use UserDefaults, that will allow you to store small sized information (like color preference) inside memory. So you can use something like this:
UserDefaults.standard.set(UIColor.red , forKey: "themePreferenceKey")
That will store Red choice in memory that'll be reachable with key themePreferenceKey later on.
For changing view/button background colors according to user's saved choice, you must fetch the value of themePreferenceKey whenever a view is Appeared, and change the colors accordingly. This can be implemented inside viewDidAppear method. Such as:
override func viewDidAppear(_ animated: Bool) {
if let preferredColor = UserDefaults.standard.object(forKey: "themePreferenceKey") as? UIColor {
self.view.backgroundColor = preferredColor
}
}

UIButton text content keeps resetting every second update

I am trying to update a button with a test value and I have noticed that every second update the button title text shows the test value for a fraction of a second but then resets to the Button's default value.
It seems to be a bug, but I wanted to see if there is a simpler explanation.
I have tried waiting up to 10 seconds before pushing the button but this seems to be consistently occurring.
Any ideas how to make UIButton function as expected?
import UIKit
class ViewController: UIViewController {
var testEntry = "its working"
#IBOutlet weak var testButton: UIButton!
#IBOutlet weak var testLabel: UILabel!
#IBAction func runTest(sender:
UIButton) {
// The button value should equal the value of the label value, but every 2nd button press of the test button results in the title of the button value resetting to the default value
dispatch_async(dispatch_get_main_queue()) {
self.testLabel.text = "\(self.testEntry)"
self.testButton.titleLabel?.text = "\(self.testEntry)"
}
}
Here is the github project.
You shouldn't be directly setting the text of the button title label, you should only set the font directly onto the label. The text should be set by calling
func setTitle(_ title: String?, forState state: UIControlState)
The text toggles because you're selecting and de-selecting the button, which is switching between some of its states which have different titles.
You should set the button title text by using the following method...
self.testButton.setTitle(self.testEntry, forState: .Normal)
instead of titleLabel property.
Swift 5
self.testButton.setTitle("hello", for: .normal)

UISliders and UILabels and viewControllers

How would I be able to increase/decrease the size of my UILabel by using UISlider which is in a different viewController?
I have a viewController1 that has the UILabel1 and I have viewController2 which has a UISlider. With the UISlider I have another label,UILabel2, just to see how big the text will be. I want UILabel1 to increase/decrease also instead of just one label to increase/decrease.
The code being used for UISLider is,
#IBOutlet weak var label: UILabel!
#IBOutlet weak var slider: UISlider!
#IBAction func sizeChanged(sender: UISlider) {
let senderValue = CGFloat(sender.value)
label.font = UIFont(name: label.font.fontName, size: senderValue)
}
This code with UILabel is for viewController2 and I want to change the size of another UILabel thats in viewController1.
This is viewController1:
import UIKit
class ViewController1: ViewController {
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var scrollView1: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView1.contentSize.height = 5000
scrollView1.contentSize.width = 375
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
This is viewController2:
#IBOutlet weak var label: UILabel!
#IBOutlet weak var slider: UISlider!
#IBAction func sizeChanged(sender: UISlider) {
let senderValue = CGFloat(sender.value)
label.font = UIFont(name: label.font.fontName, size: senderValue)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
Any help would be great.
In computer programming, when something seems difficult or complicated, you should look for ways to break it down into smaller problems that are easier to solve. Yours is a fine example. You asked:
How would I be able to increase/decrease the size of my UILabel by using UISlider which is in a different viewController?
So, what are the steps that anyone would need to perform to make this happen? There are basically three steps here:
Get a slider's value.
Send a value from one view controller to another.
Use a value to set the size of a label.
How do I get a slider's value? This is straightforward. Set the slider's target to the view controller that manages it and its action to some action in the view controller. That method will be called when the slider changes. The action will look like this:
#IBAction func sliderValueChanged(sender: UISlider) {
let value = sender.value
// do something with the value
}
How do I send data from one view controller to another? There are lots of questions on SO that cover this. Of those, Passing Data Between View Controllers is perhaps the canonical one. There are lots of options, including:
Have one view controller call a method in the other. If the view controller with the slider has a reference to the one with the label, it only has to call some method when the slider changes to pass the new value to the other controller. Or, maybe it's the view controller with the label that has a reference to the one with the slider, which is pretty typical if the slider's controller is created by the label's controller. In that case, the label's controller can call a method to retrieve the value.
Broadcast the data to anyone who is listening using notifications. When the slider changes, it's action can post a notification with the new value. Any object, including the controller with the label, can listen for that notification and act on it.
Use a proper data model. The MVC (model-view-controller) paradigm is big in Cocoa, and if your app is anything beyond trivial it should have its own data model. That model may be a reasonable place to store the slider's latest setting, and the controller with the label can read it from there when its view appears.
Stash the value somewhere. Global variables are a short path to a badly design application, but their simplicity is appealing to beginners. A better choice may be the defaults system, which at least lets the value persist when the app quits.
So, lots of options there. Forget about the slider and the label and think about how the view controllers in your app should communicate with each other. Once you figure that out, the slider setting is just one more thing that they have to say to each other. The style you choose will tell you what to put in the action method above in place of the comment.
How do I set the size of a label? It's a little unclear what you mean by setting the size. Do you want to change the font size, or the width of the label, or the width and height? In any case, there are accessors for all the properties of a label that you might want to set, so check out the docs. When the label's view controller gets a new value via one of the methods above, it should update the appropriate property of the label. You typically connect the label to an IBOutlet property in the view controller to give the controller easy access to the label.
I think, you can look at NSNotificationCenter's functionality, especially at NSNotification's userInfo:
parameter. You can pass your slider's value to userInfo from first VC and then listen to this notification in second VC.
Great example of this method in Objective-C:
https://stackoverflow.com/a/7896761

Resources