UILongPressGestureRecognizer access the button being clicked - ios

I set one UILongPressGestureRecognizer to handle four different buttons in my view, how do I access which button is being clicked in my code?
My UILongPressGestureRecognizer looks like it:
#IBAction func editText(sender: UILongPressGestureRecognizer) {
textFieldInput.hidden = false
iphoneSaveCharName.hidden = false
}
And I Want to use Long Press so that I can edit the button text
EDIT 1:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var iphoneTableView: UITableView!
#IBOutlet weak var textFieldInput: UITextField!
#IBOutlet weak var iphoneSaveCharName: UIButton!
#IBOutlet weak var charOne: UILabel!
#IBOutlet weak var charTwo: UILabel!
#IBOutlet weak var charTree: UILabel!
#IBOutlet weak var charFour: UILabel!
#IBOutlet weak var test1: UIButton! //button that I am clicking on!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Function I made so I can save the user input
#IBAction func iphoneSaveTextInput(sender: UIButton) {
let textData = textFieldInput.text
textFieldInput.hidden = true
iphoneSaveCharName.hidden = true
charTwo.text = textData
}
// This is the LongPress Action
#IBAction func editText(sender: UILongPressGestureRecognizer) {
textFieldInput.hidden = false
iphoneSaveCharName.hidden = false
func longPressMethod(gesture: UILongPressGestureRecognizer) {
println(gesture.view)
if gesture.view is UIButton {
let test1 = gesture.view as UIButton
println(test1)
}
}
}
}
Edit 2: Layout
Edit 3: New ViewController
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var iphoneTableView: UITableView!
#IBOutlet weak var textFieldInput: UITextField!
#IBOutlet weak var iphoneSaveCharName: UIButton!
#IBOutlet weak var charOne: UIButton!
#IBOutlet weak var charTwo: UIButton!
#IBOutlet weak var charThree: UIButton!
#IBOutlet weak var charFour: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func iphoneSaveTextInput(sender: UIButton) -> Void{
let textData = textFieldInput.text
textFieldInput.hidden = true
iphoneSaveCharName.hidden = true
}
#IBAction func editText(sender: AnyObject) {
if sender is UILongPressGestureRecognizer &&
sender.state == UIGestureRecognizerState.Began {
textFieldInput.hidden = false
iphoneSaveCharName.hidden = false
// func iphoneSaveTextInput(sender: UIButton){
// var textData = textFieldInput.text
// textFieldInput.hidden = true
// iphoneSaveCharName.hidden = true
//
// }
let button = sender.view as UIButton
println(button)
if button.tag == 1{
charOne.setTitle("textData", forState: .Normal)
} else if button.tag == 2{
charTwo.setTitle("textData2", forState: .Normal)
} else if button.tag == 3{
charThree.setTitle("textData3", forState: .Normal)
} else if button.tag == 4{
charFour.setTitle("textData4", forState: .Normal)
}
}
}
}
Answer:
This is the final view control:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var iphoneTableView: UITableView!
#IBOutlet weak var textFieldInput: UITextField!
#IBOutlet weak var iphoneSaveCharName: UIButton!
#IBOutlet weak var charOne: UIButton!
#IBOutlet weak var charTwo: UIButton!
#IBOutlet weak var charThree: UIButton!
#IBOutlet weak var charFour: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func iphoneSaveTextInput(sender: UIButton) -> Void{
let textData = textFieldInput.text
textFieldInput.hidden = true
iphoneSaveCharName.hidden = true
}
#IBAction func editText(sender: AnyObject) {
if sender is UILongPressGestureRecognizer &&
sender.state == UIGestureRecognizerState.Began {
textFieldInput.hidden = false
iphoneSaveCharName.hidden = false
// func iphoneSaveTextInput(sender: UIButton){
// var textData = textFieldInput.text
// textFieldInput.hidden = true
// iphoneSaveCharName.hidden = true
//
// }
let button = sender.view as UIButton
println(button)
if button.tag == 1{
charOne.setTitle("textData", forState: .Normal)
} else if button.tag == 2{
charTwo.setTitle("textData2", forState: .Normal)
} else if button.tag == 3{
charThree.setTitle("textData3", forState: .Normal)
} else if button.tag == 4{
charFour.setTitle("textData4", forState: .Normal)
}
}
}
}
I would mostly like to give you all a best answer since everybody helped me out! I had to create one Long Press for each button, otherwise code will get confused.

Your question has introduced me to a really cool feature, so thanks! :)
It turns out that if you attach a UILongPressGestureRecognizer to a UIButton in a storyboard and attach that button and gesture to an IBAction within your swift class, that IBAction method can recognize whether the touch is a tap or long press! Pretty cool, huh?
So first off, make sure that each UIButton has its own unique UILongPressGestureRecognizer; then you can edit your code like so, so that it's able to identify which button is being pressed and whether that press is either a simple tap or UILongPressGestureRecognizer:
// Connect both your button *and* its gestures to the
// `IBAction` method so that the function will be called
// no matter what kind of gesture it recognizes -- tap,
// long press, or otherwise.
#IBAction func buttonSelected(sender: AnyObject) {
// But to see if the gesture is a long press, you can
// simply check the sender's class and execute the code
// when the gesture begins.
if sender is UILongPressGestureRecognizer &&
sender.state == UIGestureRecognizerState.Began {
// These two lines are originally from your
// editText method
textFieldInput.hidden = false
iphoneSaveCharName.hidden = false
// Then to identify which button was long pressed you
// can check the sender's view, to see which button IBOutlet
// that gesture's view belongs to.
// Method #1:
let button = sender.view as UIButton
if button == thisButton {
} else if button == thatButton {
}
...
// Or you can check the gesture view's tag to see which
// button it belongs to (i.e. whichever button has a matching
// tag).
// Method #2:
let button = sender.view as UIButton
if button.tag == 1 {
} else if button.tag == 2 {
}
...
}
// Else if it's not a long press gesture, perform
// whatever action you'd like to accomplish during a
// normal button tap
else if !(sender is UILongPressGestureRecognizer) {
// These lines are originally from your
// iphoneSaveTextInput
let textData = textFieldInput.text
textFieldInput.hidden = true
iphoneSaveCharName.hidden = true
}
}
But if you want to continue to keep the UILongPressGestureRecognizer IBAction separate from the UIButton's IBAction (i.e. link the UIButtons to iphoneSaveTextInput: and your UILongPressGestureRecognizers to editText:), that should be OK too. Just keep your iphoneSaveTextInput: method as is, and update your editText: method like so:
// This is the LongPress Action
#IBAction func editText(sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizerState.Began {
textFieldInput.hidden = false
iphoneSaveCharName.hidden = false
// Then to identify which button was long pressed you
// can check the sender's view, to see which button IBOutlet
// that gesture's view belongs to.
// Method #1:
let button = sender.view as UIButton
if button == thisButton {
} else if button == thatButton {
}
...
// Or you can check the gesture view's tag to see which
// button it belongs to (i.e. whichever button has a matching
// tag).
// Method #2:
let button = sender.view as UIButton
if button.tag == 1 {
} else if button.tag == 2 {
}
...
}
}

You don't want to use the same gesture recognizer across different views:
Can you attach a UIGestureRecognizer to multiple views?
The view property of the gesture recognizer is probably what you would want to check but you want different gesture recognizers for each view.
If you want, they could all be linked to the same selector, though, and you could access the incoming recognizer's view that way.

A general way to make a button have different actions based on how long you press it, looks like this (timer is a property),
#IBAction func buttonDown(sender: UIButton) { // connected to touchDown
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "handleTimer", userInfo: sender, repeats: false)
}
#IBAction func buttonUp(sender: UIButton) { // connected to touchUpInside
if timer != nil {
timer.invalidate()
println("change view")
}
}
func handleTimer() {
var button = timer.userInfo as UIButton
timer = nil
button.setTitle("New Title", forState: .Normal)
}

Related

How to remove popView if we tap anywhere in the background except tapping in popView in swift

I have created one popView with textfield and button in ViewController. if i click button then popView is appearing, and i am able to enter text in textfield and submit is working, and if i tap anywhere in view also i am able to remove popView, but here i want if i tap on anywhere in popView i don't want to dismiss popView, Please help me in the code.
here is my code:
import UIKit
class PopUPViewController: UIViewController {
#IBOutlet weak var popView: UIView!
#IBOutlet weak var inputField: UITextField!
#IBOutlet weak var textLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
popView.isHidden = true
// Do any additional setup after loading the view.
}
#IBAction func butnAct(_ sender: Any) {
view?.backgroundColor = UIColor(white: 1, alpha: 0.9)
popView.isHidden = false
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PopUPViewController.dismissView))
view.addGestureRecognizer(tap)
}
#objc func dismissView() {
self.popView.isHidden = true
view?.backgroundColor = .white
}
#IBAction func sendButton(_ sender: Any) {
self.textLabel.text = inputField.text
}
}
In my code if i tap anywhere in the view popView is removing even if i tap on popView also its removing, i don't need that, if i tap on popView then popView need not to be remove.
Please help me in the code
You can override the touchesBegan method which is triggered when a new touch is detected in a view or window. By using this method you can check a specific view is touched or not.
Try like this
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if touch?.view != self.popView {
dismissView()
}
}
func dismissView() {
self.popView.isHidden = true
view?.backgroundColor = .white
}
It's not the way I would have architected this, but to get around the problem you face you need to adapt your dismissView method so that it only dismisses the view if the tap is outside the popView.
To do this modify your selector to include the sender (the UITapGestureRecogniser )as a parameter:
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PopUPViewController.dismissView(_:)))
and then in your function accept that parameter and test whether the tap is inside your view, and if so don't dismiss the view:
#objc func dismissView(_ sender: UITapGestureRegognizer) {
let tapPoint = sender.location(in: self.popView)
if self.popView.point(inside: tapPoint, with: nil)) == false {
self.popView.isHidden = true
view?.backgroundColor = .white
}
}
Your Popup view is inside the parent view of viewcontroller that's why on tap of popview also your popview is getting hidden.
So to avoid just add a view in background and name it bgView or anything what you want and replace it with view. And it will work fine .
Code:
#IBOutlet weak var bgView: UIView!//Add this new outlet
#IBOutlet weak var popView: UIView!
#IBOutlet weak var inputField: UITextField!
#IBOutlet weak var textLabel: UILabel!
#IBOutlet weak var submitButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
popView.isHidden = true
}
#IBAction func butnAct(_ sender: Any) {
bgView.backgroundColor = UIColor(white: 1, alpha: 0.9)//change view to bgView[![enter image description here][1]][1]
popView.isHidden = false
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissView))
bgView.addGestureRecognizer(tap)//change view to bgView
}
#objc func dismissView() {
self.popView.isHidden = true
bgView.backgroundColor = .white//change view to bgView
}
#IBAction func sendButton(_ sender: Any) {
self.textLabel.text = inputField.text
}

Disable / Enable a button in Xcode

Hi i'm new with Swift programming.
What im trying to do is Disable my button (signIn) in viewDidLoad and only enable when the textfields have text in them. Here's what i've achieved so far. (not much though!)
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
signIn.isEnabled = false
// Do any additional setup after loading the view, typically from a nib.
}
#IBOutlet weak var emailtxt: UITextField!
#IBOutlet weak var passwordtxt: UITextField!
#IBOutlet weak var signIn: UIButton!
I need help to create a function in signIn that keeps button disabled until text fields (emailtxt & passwordtxt) have text in them and then proceed.
Glad if anyone can sort me.
Thanks in advance!
First add these for all of your textFields in viewDidLoad():
emailtxt.addTarget(self, action: #selector(textFieldDidChange(_:)),
for: UIControlEvents.editingChanged)
passwordtxt.addTarget(self, action: #selector(textFieldDidChange(_:)),
for: UIControlEvents.editingChanged)
Then use this:
#objc func textFieldDidChange(_ textField: UITextField) {
self.buttonIsEnabled()
}
func buttonIsEnabled() {
var buttonIsEnabled = true
defer {
self.signIn.isEnabled = buttonIsEnabled
}
guard let emailtxt = self.emailtxt.text, !emailtxt.isEmpty else {
addButtonIsEnabled = false
return
}
guard let passwordtxt = self. passwordtxt.text, ! passwordtxt.isEmpty else {
addButtonIsEnabled = false
return
}
}
I use this way in my codes and it works well.
Even you can add more methods for additional checking to buttonIsEnabled, like:
self.checkEmailIsValid(for: emailtxt)
Of course you should handle this method before:
func checkEmailIsValid(for: String) {
//...
}
Set ViewController as delegate for emailtxt and passwordtxt like this,
override func viewDidLoad() {
super.viewDidLoad()
signIn.isEnabled = false
emailtxt.delegate = self
passwordtxt.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
Conform your ViewController to UITextFieldDelegate and enable/disable as the text input is finished,
extension ViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
if emailtxt.text?.isEmpty == false && passwordtxt.text?.isEmpty == false {
signIn.isEnabled = true
} else {
signIn.isEnabled = false
}
}
}
Here is the fix for your code you shared.
import UIKit
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
}
extension SignInVC: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
if emailtxt.text?.isEmpty == false && passwordtxt.text?.isEmpty == false {
signIn.isEnabled = true
} else {
signIn.isEnabled = false
}
}
}
class SignInVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
signIn.isEnabled = false
emailtxt.delegate = self
passwordtxt.delegate = self
self.hideKeyboardWhenTappedAround()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var emailtxt: UITextField!
#IBOutlet weak var passwordtxt: UITextField!
#IBOutlet weak var signIn: UIButton!
}
What I would do is create an IBAction from one of your text fields, and set the event to Editing Changed:
The code should look like this:
#IBAction func textFieldEditingDidChange(_ sender: UITextField) {
}
You can then connect that same outlet to both of your text fields by dragging from the outlet to your remaining field. If you've connected both correctly, clicking on the circle to the left of your IBAction should show two text fields:
The action will now be fired every time text changes in either of your fields.
Then, at the top of the file, I'd create a computed property that returns false unless there is something in both fields:
var shouldEnableButton: Bool {
guard let text1 = textField1.text, let text2 = textField2.text else {
return false
}
return text1.isEmpty && text2.isEmpty ? false : true
}
Finally, we add shouldEnableButton to our IBAction:
#IBAction func textFieldEditingDidChange(_ sender: UITextField) {
button.isEnabled = shouldEnableButton
}
Important
When you connect your second text field to the outlet, it will incorrectly assign Editing Did End as its event:
Delete this event and click and drag from Editing Changed to your IBAction:
Use SwiftValidator
https://github.com/SwiftValidatorCommunity/SwiftValidator
by this, you will set validation of email & password like below
import SwiftValidator
let validator = Validator()
validator.registerField(emailTextField, errorLabel: emailErrorLabel, rules: [RequiredRule(), EmailRule(message: "Invalid email")])
// MARK: - ValidationDelegate
extension ViewController: ValidationDelegate {
func validationSuccessful() {
self.loginUser()
}
func validationFailed(_ errors:[(Validatable ,ValidationError)]) {
for (field, error) in errors {
//Handle as per need - show extra label - shake view etc
/*
if let field = field as? UITextField {
Utilities.shakeTheView(shakeView: field)
}
error.errorLabel?.text = error.errorMessage
error.errorLabel?.isHidden = false
*/
}
}
}

How to hide button and disable button

I'm trying to create small restaurant app for employees. There I have table numbers as a button if the user clicks that button I want that clicked button to be disabled and I want textfield and another ok button to appear. And if I click on disable button I want that to be enabled.
import UIKit
class ViewController: UIViewController {
var total = 0
#IBOutlet weak var okButton: UIButton!
#IBOutlet weak var userInput: UILabel!
#IBOutlet weak var userValue: UITextField!
#IBAction func okButton(_ sender: UIButton) {
if userValue.text != nil{
userInput.text = String(0)
let userValueint: Int? = Int(userValue.text!)
total = total + userValueint!
let convertText = String(total)
userInput.text = convertText
userValue.text = String(0)
userValue.isHidden = true
okButton!.isHidden = true
} else {
print("Please Inter values")
}
}
#IBAction func buttenPressed(_ sender: UIButton) {
userValue.isHidden = false
okButton.isEnabled = true
}
override func viewDidLoad() {
super.viewDidLoad()
userValue.isHidden = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
okButton.isHidden = false
}
}
So far I'm able to hide textField at the beginning and able to enabled when table button is clicked, but I can't hide ok button and disable the table button. Any suggestion?
First of all, you can't clicked a disabled button. Second, use viewDidLoad instead of viewWillAppear.
I guess your table button is sender so disable sender and show ok button
#IBAction func buttenPressed(_ sender: UIButton) {
sender.isEnabled = false
userValue.isHidden = false
okButton.isHidden = false
okButton.isEnabled = true
}

Radio Button Group Swift 3 Xcode 8

I have searched various sources and could not find a clear and simple solution for creating the equivalent of a radio button group in Swift 3 with Xcode 8.3 for an iOS application.
For example if I have 3 buttons in one group and only one should be selected at a time. Currently I am implementing this by changing the state of 2 buttons in the group to not selected when the other one is selected and vice versa.
#IBAction func buttonA(_ sender: Any) {
buttonB.isChecked = false
buttonC.isChecked = false
}
#IBAction func buttonB(_ sender: Any) {
buttonA.isChecked = false
buttonC.isChecked = false
}
#IBAction func buttonC(_ sender: Any) {
buttonA.isChecked = false
buttonB.isChecked = false
}
However I would expect a more efficient way to do this.
Any help on a more efficient solution will be appreciated.
You can connect all your button's IBAction to one single method.
#IBAction func buttonClick(_ sender: UISwitch) { // you're using UISwitch I believe?
}
You should add all the buttons into an array:
// at class level
var buttons: [UISwitch]!
// in viewDidLoad
buttons = [buttonA, buttonB, buttonC]
Then, write the buttonClick method like this:
buttons.forEach { $0.isChecked = false } // uncheck everything
sender.isChecked = true // check the button that is clicked on
Alternatives:
Try using a UITableView. Each row contains one option. When a row is selected, change that row's accessoryType to .checkMark and every other row's to .none.
If you are too lazy, try searching on cocoapods.org and see what other people have made.
Just make a single selector for all three button's touchUpInside event, and set radio_off image for normal state and radio_on image for selected state in your IB, then only you have to connect btnClicked method to all button's touchUpInside event
class ViewController: UIViewController {
#IBOutlet weak var btnFirst:UIButton!
#IBOutlet weak var btnSecond:UIButton!
#IBOutlet weak var btnThird:UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func btnClicked(sender:UIButton){
let buttonArray = [btnFirst,btnSecond,btnThird]
buttonArray.forEach{
$0?.isSelected = false
}
sender.isSelected = true
}
Depending on your UI, you could take multiple approaches.
UITableView - Use a UITableView with a checkmark decorator. If your layout for these radio buttons is fairly traditional, this is the correct paradigm. If the layout is a grid instead of a list, you could use UICollectionView.
You can use the func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) in UITableViewDelegate to capture the selection. You can call indexPathForSelectedRow on the tableView when you want to commit the change to determine which cell was selected.
Apple's tutorial on UITableView can be found at:
https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/CreateATableView.html
Manage a group of UIButtons - You could store an array of references to UIButton objects that are part of your radio button group.
protocol RadioButtonDelegate: class {
func didTapButton(_ button: UIButton)
}
class RadioButtonGroup {
private var buttons: [UIButton] = []
weak var delegate: RadioButtonDelegate?
var selectedButton: UIButton? { return buttons.filter { $0.isSelected }.first }
func addButton(_ button: UIButton) {
buttons.append(button)
}
#objc private func didTapButton(_ button: UIButton) {
button.isSelected = true
deselectButtonsOtherThan(button)
delegate?.didTapButton(button)
}
private func deselectButtonsOtherThan(_ selectedButton: UIButton) {
for button in buttons where button != selectedButton {
button.isSelected = false
}
}
}
class MyView: UIView {
private var radioButtonGroup = RadioButtonGroup()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let button1 = UIButton(type: .custom)
button1.setTitle("Eeeny", for: .normal)
let button2 = UIButton(type: .custom)
button2.setTitle("Meeny", for: .normal)
let button3 = UIButton(type: .custom)
button3.setTitle("Miny", for: .normal)
self.radioButtonGroup.addButton(button1)
self.radioButtonGroup.addButton(button2)
self.radioButtonGroup.addButton(button3)
addSubview(button1)
addSubview(button2)
addSubview(button3)
}
}
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var maleLB: UIButton!
#IBOutlet weak var femaleLB: UIButton!
#IBOutlet weak var otherLB: UIButton!
var gender = "Male"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if gender == "Male"{
femaleLB.isSelected = true
}
}
#IBAction func maleBtn(_ sender: UIButton) {
if sender.isSelected {
sender.isSelected = false
femaleLB.isSelected = false
otherLB.isSelected = false
}
else{
sender.isSelected = true
femaleLB.isSelected = false
otherLB.isSelected = false
}
}
#IBAction func femaleBtn(_ sender: UIButton) {
if sender.isSelected {
sender.isSelected = false
maleLB.isSelected = false
otherLB.isSelected = false
}
else{
sender.isSelected = true
maleLB.isSelected = false
otherLB.isSelected = false
}
}
#IBAction func otherBtn(_ sender: UIButton) {
if sender.isSelected {
sender.isSelected = false
maleLB.isSelected = false
femaleLB.isSelected = false
}
else{
sender.isSelected = true
maleLB.isSelected = false
femaleLB.isSelected = false
}
}
}

How can I change UIStepper value when changed from UITextField?

I'm very new to all of this and I found some code that got me understanding some of this syntax. I'm trying to create a textfield that lets me type in a value that updates the stepper's value. The stepper currently works (updates the uitextfield) but when I change the value in the textfield it doesn't update the stepper's value, so when I click on the stepper, it reverts back to whatever value it was before I typed in a value... Can anyone tell me why the two functions STracksValueDidChange and CTrackValueDidChange have errors?
Here's my code so far:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var STracks: UITextField!
#IBOutlet weak var STracksStepper: UIStepper!
#IBOutlet weak var CTracks: UITextField!
#IBOutlet weak var CTrackStepper: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
STracksStepper.autorepeat = true
STracksStepper.maximumValue = 100.0
STracksStepper.minimumValue = 2.0
STracksStepper.stepValue = 2.0
print(STracksStepper.value)
STracks.text = "\(Int(STracksStepper.value))"
STracksStepper.addTarget(self, action: "SstepperValueDidChange:", forControlEvents: .ValueChanged)
STracks.addTarget(self, action: "STextValueDidChange:", forControlEvents: .ValueChanged)
CTrackStepper.autorepeat = true
CTrackStepper.maximumValue = 100.0
CTrackStepper.minimumValue = 2.0
CTrackStepper.stepValue = 2.0
print(CTrackStepper.value)
CTracks.text = "\(Int(CTrackStepper.value))"
CTrackStepper.addTarget(self, action: "CstepperValueDidChange:", forControlEvents: .ValueChanged)
CTracks.addTarget(self, action: "CTextValueDidChange:", forControlEvents: .ValueChanged)
}
//Steppers will update UITextFields
func SstepperValueDidChange(stepper: UIStepper) {
let stepperMapping: [UIStepper: UITextField] = [STracksStepper: STracks]
stepperMapping[stepper]!.text = "\(Int(stepper.value))"
}
func STracksValueDidChange(SText: UITextField) {
let STextMapping: [UITextField: UIStepper] = [STracks: STracksStepper]
STextMapping[SText]!.value = "(SText.text)"
}
func CstepperValueDidChange(stepper: UIStepper) {
let stepperMapping: [UIStepper: UITextField] = [CTrackStepper: CTracks]
stepperMapping[stepper]!.text = "\(Int(stepper.value))"
}
func CTrackValueDidChange(CText: UITextField) {
let CTextMapping: [UITextField: UIStepper] = [CTracks: CTrackStepper]
CTextMapping[CText]!.value = "(CText.text)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Try something like this.
CTrackStepper.value = Double(Textfield.text)
I am not so sure what the mapping is in your code.
But i don't think you need it for changing the value.
Update, made a project my self:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textfield: UITextField!
#IBOutlet weak var stepper: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func stepperValueChanged(sender: UIStepper) {
textfield.text = String(sender.value)
}
#IBAction func valueChanged(sender: UITextField) {
if Double(sender.text!) != nil {
stepper.value = Double(sender.text!)!
}
}
}
For steppervaluechanged and valuechanged just drag from uistepper and textfield and choose action and change the Anyobject to Uistepper of Uitextfield.
Good luck :)

Resources