Im currently developing a iOS app in which im going to keep track of our warehouse stock. It's a pretty simple app an just contains a lable and an stepper. The app is pretty much finished, but i don't get how to save the changed value of the label. I want to save it automatically so that when someone presses the "+" on the stepper, the value should save without pressing a extra save button
Current code:
//montageplatte
#IBOutlet weak var lbl_montageplatte: UILabel!
#IBAction func stepper_montageplatte(_ sender: UIStepper)
{
lbl_montageplatte.text = Int(sender.value).description
}
you can save it in UserDefaults.
#IBAction func stepper_montageplatte(_ sender: UIStepper) {
lbl_montageplatte.text = Int(sender.value).description
UserDefaults.standard.set(String(sender.value), forKey: "lblMontageplatte")
}
To get back value you can do as follow...
if let lblValue = UserDefaults.standard.object(forKey: "lblMontageplatte") as? String {
print(lblValue)
lbl_montageplatte.text = lblValue
}
Simple solution:
In the custom cell create an outlet for the stepper and a NSKeyValueObservation property
#IBOutlet weak var stepper : UIStepper!
var stepperObservation : NSKeyValueObservation?
In cellForRow in the controller add the key value observer
cell.stepperObservation = cell.stepper.observe(\.value, options: [.new]) { (stepper, change) in
print(change.newValue!)
}
Rather than printing the new value update the model (the item for the particular index path) and save the datasource array if necessary.
Related
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: ", ")
}
}
I am trying to add users names that they have put in a textfield to a basic array. I don’t even know where to start!
The functionality basically is this:
User adds a name in text field
Name is stored in an array so it can be referenced again somewhere else.
As you can tell I’m new to Xcode. I have been taking classes all of which have failed to explain this process. Any help is good Help ! Please :):)
// my view controller so far
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var name1: UITextField!
#IBOutlet weak var name2: UITextField!
#IBOutlet weak var name3: UITextField!
var namesArray : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
name1.delegate = self
name2.delegate = self
name3.delegate = self
self.namesArray.append(self.name1.text!)
self.namesArray.append(self.name2.text!)
self.namesArray.append(self.name3.text!)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if textField.returnKeyType == UIReturnKeyType.done {
self.namesArray.append(self.name1.text!)
print(namesArray)
}
return true
}
I am going to assume you have all your logic mashed into one view controller since you are still learning and not worried about larger architecture decisions yet.
At the top of your class, you need an array variable:
// Creates an array and initializes it to be empty.
var userNames: [String] = []
I suspect you also have a button, so that when you press on the button, it grabs the text from the textfield and stores it in the array. You need to set up an IBAction method for that button, and in that method...
// Grab the text, save it in the array, and clear the text.
self.userNames.append(self.myTextField.text)
self.myTextField.text = ""
Later on, you can easily see the list of userNames by accessing self.userNames. e.g.:
let firstUser = self.userNames.first
let lastUser = self.userNames.last
let user47 = self.userNames[46] // assuming you have that many users
I am struggling for some hours at a problem. Basically, I have a simple Swift app. It goes like this. In my 1st view controller I have 3 text fields I want to fill them with information and a "Next" button.
Pressing the "Next" button will send me to a new UIViewController where I will have a "Back" button. Upon pressing the back button, I will be send back to 1st page with the 3 text fields.
What I want is: if I complete the text fields with informations, press Next and then Back, I want the text fields to be filled with that information.
I managed to move between the views with buttons, but I can't save the information. Can you provide me a little help?
#IBOutlet weak var txtb1: UITextField!
#IBOutlet weak var txtb2: UITextField!
#IBOutlet weak var txtb3: UITextField!
#IBAction func next(sender: AnyObject) {
text1 = self.txtb1.text!
text2 = self.txtb2.text!
text3 = self.txtb3.text! }
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if (!text1)
{
txtb1.text = text1
}
}
If you are wanting to pass variables to different views you will have to use the prepareForSegue function before you segue into that view controller.
This allows the variables to be accessed by the view controller.
Override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)
{
if segue.identifier == "segue_name"
{
let theDestination = segue.destinationViewController as! newViewController
theDestination.variable = "testing"
theDestination.variable2 = "testing2"
}
}
Then inside your second view controller you will have to declare variable and variable2 as shown:
var variable:String!
var variable2:String!
These will then be able to be used in the second view controller inside the viewDidLoad method.
Ok. I managed to fix a little of the problem, that button wasn't linked accordingly so the function was not executing. Here it is the code:
var text1 = ""
#IBOutlet weak var txtb1: UITextField!
#IBAction func next(sender: AnyObject) {
text1 = self.txtb1.text! // text1 = "I am taking value"
}
// when i press the back button
override func viewDidLoad() {
super.viewDidLoad()
if (!numarInmatriculare.isEmpty)
{
txtb1.text = text1 //here text1 = Null. the value is not saved
}
}
I want the value to be saved and displayed back on text field.
I also tried to use static varibiles but I am prompet with error.
static var numar:String = ""
numar = text1
//static member 'numar'cannot be used on instance of type 'viewcontroller'
You no need to do anything for this case, once text field filed then you clicking next button you wrote some code below i shown
text1 = self.txtb1.text!
text2 = self.txtb2.text!
text3 = self.txtb3.text!
Please first you remove the code,Once data filled in text filed, its automatically retain, after you clicking next button then come back it automatically it will retain, when your current view is poping then only your data will deallocate.
I made an app where I save a label that I can make it go up or down one number in my app. But if I lose out of my app and open it back up, if i make the label go up again than it resets back to zero and goes to one. This is because I have to set the variable value to zero. Here is my code:
#IBOutlet var goal: UILabel!
#IBAction func player1button(sender: AnyObject)
{
NSUserDefaults.standardUserDefaults().setValue(goal.text!, forKey:"firstGoal")
}
var goal1 = 0
#IBAction func goalUp(sender: AnyObject)
{
goal1++
goal.text = "\(goal1)"
}
override func viewDidLoad()
{
super.viewDidLoad()
goal.text = (NSUserDefaults.standardUserDefaults().objectForKey("firstGoal") as? String)
}
Im saving the goal number then calling it back later in the text. Please show me a way to fix it so it just adds on to the previous number.
in viewDidLoad() add
goal1 = Int((NSUserDefaults.standardUserDefaults().objectForKey("firstGoal") as? String)!)
this will set the int variable you are using to keep track of the goals to the correct value when the app loads. currently you are only setting the text label to the correct value.
or you can simply make var goal1 a global variable , just after the imports and before the class keyword , in case you don't need to keep the data till the next time you open the app itself
I have created a tableviewcontroller, with a dynamic prototype cell. Within this view the user has an option to type in a review of a location from a button press as well as can rate the location on a scale of 1 to 10 with a UI Slider. The review is done with a UIAlertController within the tableviewcontroller - but the UISlider is within the cell itself. I am trying to save both pieces of data to core data within the tableviewcontroller. But the UISlider rating value is not available within the tableviewcontroller - is there a way to reference it in tableview from the cell or do I need to have two separate save functions? Here is some of my code thus far - within the tableview controller it doesn't recognize the variable assigned to the UISLider value in the prototype cell. Thanks in advance for any help!
In my tableviewcell:
class WineryInfoTableViewCell: UITableViewCell {
#IBOutlet weak var ratingLabel: UILabel!
#IBOutlet weak var sliderbutton: UISlider!
#IBAction func sliderValueChanged(sender: UISlider) {
var ratingValue = Float(sender.value)
var roundedRatingValue = roundf(ratingValue/0.5)*0.5
ratingLabel.text = "\(roundedRatingValue)"
}
in my tableviewcontroller
#IBAction func save() {
if let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext {
myRatingData = NSEntityDescription.insertNewObjectForEntityForName("WineryReview", inManagedObjectContext: managedObjectContext) as wineryReview
myRatingData.wineryName = wineryNames
//myRatingData.rating = ratingLabel.text how do I call this for saving?
myRatingData.review = myRatingEntry
var e:NSError?
if managedObjectContext.save(&e) != true {
println("insert error: \(e!.localizedDescription)")
return
}
}
// If all fields are correctly filled in, extract the field value
println("Winery: " + myRatingData.wineryName)
println("Review: " + myRatingData.review)
//println("Rating: " + ratingLabel.text!) how do I call this for saving?
}
I'm still new at Swift, but I think I may have an answer to a part of your dilemma. To reference the UISlider in your table cell, you can use 'tags' to get a reference to it.
For example:
let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.someCell, forIndexPath: indexPath) as UITableViewCell
let slider = cell.viewWithTag(100) as UISlider
In the above example, I would have used assigned the UISlider with a tag of 100, so I am able to get a reference to it using the cell.viewWithTag(100).
Forgive me if this doesn't work!
You could pass a WineryReview object into the cell and set its rating directly from sliderValueChanged.
In cellForRowAtIndex:
cell.wineryReview = myReviewData
In TableViewCell:
#IBOutlet weak var ratingLabel: UILabel!
#IBOutlet weak var sliderbutton: UISlider!
var wineryReview: WineryReview?
#IBAction func sliderValueChanged(sender: UISlider) {
var ratingValue = Float(sender.value)
var roundedRatingValue = roundf(ratingValue/0.5)*0.5
wineryReview.rating = roundedRatingValue
ratingLabel.text = "\(roundedRatingValue)"
}
You could call save on the context from the TableViewController if you like. I did something very similar to this in a project.