Swift : Set minimum/maximum DatePicker to other DatePicker - swift

Based on my previous question in here . I have two datePicker let say A and B. I want to set maximum of A is B.date and minimum of B is A.date.
But when i change the B value, the A maximum value still in old B maximum value. I dont have any idea about this.
let date = NSDate()
self.datePickerFrom.maximumDate = date as Date
self.datePickerTo.minimumDate = datePickerFrom.date
Any sugest and answer will helpfull for me. Thanks in Advance.

You need to tell some function in your view controller that the date pickers have changed. To do that, declare some #IBAction in your view controller that looks like this:
#IBAction func datePickerChanged(sender: UIDatePicker)
{
print("date has been set to \(sender.date)")
}
Then click on your date pickers in your storyboard or XIB file and connect the "Valued Changed" event to this new method.
Then try running it to see if the print line prints in the console.
If it does, you can fill out more of that function. Perhaps something like this:
#IBAction func datePickerChanged(sender: UIDatePicker)
{
if sender == self.datePickerFrom
{
self.datePickerTo.minimumDate = sender.date
}
if sender == self.datePickerTo
{
self.datePickerFrom.maximumDate = sender.date
}
}

Related

How to link text fields to functions

I have to create an app, with a label, a text box and a button, that will take the text that the user inputs and test if it is a palindrome and true a yes or no. It requires that I write the palindrome function in another file and call it when the button is press. The return from the function will also have to be displayed in the label field.
I have written and tested out the function but I don't know how connect it with the 3 objects on my app. They didn't teach how to do this yet in the course and googling the terms "linking text field to function in swift" only confused me more.
How should I go about learning how to do this? What terms should I search for to learn about this? I also included my palindrome funciton as reference.
func isPalindrome(word: String) -> Bool{
let word2 = word
let reversedWord = String(word.reversed())
if word2 == reversedWord {
return true
} else {
return false
}
}
isPalindrome(word: "racecar")
I presume that you know how to connect elements from storyboard to your view controller.
Link your textfield to your ViewController
#IBOutlet weak var textfield: UITextField!
then your button.
let text = textfield.text
#IBAction func checkBtn(_ sender: Any) {
isPalindrome(word: text!)
}
func isPalindrome(word: String) -> Bool{
let word2 = word
let reversedWord = String(word.reversed())
if word2 == reversedWord {
print("Is Palindrome")
return true
} else {
print("Isn't Palindrome")
return false
}
}
Also I don't think that you need to return something, except you want to use it.
for example:
if isPalindrome(word: text!){
//do something
} else{
//do something
}
If you are using storyboard, check how the #IBAction and IBOutlet works. its a visual way to link objects from storyboard into your code. If you created these label, textfield, button from code then checkout the addTarget method of UIButton for how to listen for click events.

edit a TextView in a TableView cell in swift

I'm stuck: I have a TableView populated by .xib cells that I made. Each of these cells contains an editable TextView.
I'm trying to save on my Firebase database the text that the user input in those TextViews. I don't want to implement any button, the text should be saved as soon as the TextView editing end.
I tried to connect the TextView from the .xib file to the UITableViewCell class but it doesn't allow me to connect it as an IBAction but only as outlet or outlet connection.
Please Help me, thanks!
screenshot
You need to implement the UITextFieldDelegate in your
UITableViewCell class.
Connect the delegate of the UITextView to the cell class.
Do whatever you want in the func textViewDidEndEditing(UITextView) which you need to implement in your cell class.
Here you can read more: https://developer.apple.com/documentation/uikit/uitextviewdelegate/1618603-textviewshouldendediting?changes=_2
I solved replacing the TextViews with TextFields that could look the same but could be linked to the UITableViewCell.swift as IBAction.
Thus I wrote the code to update the "comments" section of my database inside the IBAction:
#IBAction func commentTextFieldToggle(_ sender: UITextField) {
if commentTextField.text != "" {
let comment = commentTextField.text
// I declared the next 7 constants to retreive the exact position of the string "comment" that I want to change
let date = dateLabel.text!
let time = timeLabel.text!
let year = date.suffix(4)
let day = date.prefix(2)
let partialMonth = date.prefix(5)
let month = partialMonth.suffix(2)
//I use this "chosenDate" constant to retreive the database query that I previously saved using the date in the below format as index:
let chosenDate = "\(year)-\(month)-\(day) at: \(time)"
let commentsDB = Database.database().reference().child("BSL Checks")
commentsDB.child((Auth.auth().currentUser?.uid)!).child(String(chosenDate)).child("Comments").setValue(comment) {
(error, reference) in
if error != nil {
print(error!)
} else {
print("User Data saved successfully")
}
}
}
}

How to delete a character from a UI Label in Swift?

I am new to Swift and I am having issues with deleting a character from a UI Label that I have created. I am trying to make a simple phone dailer app, and I am trying ti implement a backspace button. My UI Label is called DailerLabel, and I know I'm supposed to use the dropLast() function but I keep running into issues about mismatching types or unwrappers. I am not really sure what I am supposed to do here. I tried the thing in the commented code which didn't work, and then I tried what I listed below which doesn't either. Could anyone help me?
#IBAction func backspaceButtonPressed(_ sender: UIButton) {
if (!((DailerLabel.text?.isEmpty)!)) {
// DailerLabel.text?.substring(to: (DailerLabel.text?.index(before: (DailerLabel.text?.endIndex)!))!)
let temp = DailerLabel.text
temp?.dropLast()
DailerLabel.text = temp
}
You can try this one, replace label with your own UILabel
var name: String = label.text! //shauket , for example
name.remove(at: name.index(before: name.endIndex))
print(name) //shauke
label.text = name
print(label.text!)
You are very close. dropLast actually returns the string without the last character and you haven't stored that to anything so there is no change. You also have to conver back to String from Substring.
#IBAction func backspaceButtonPressed(_ sender: UIButton) {
if (!((DailerLabel.text?.isEmpty)!)) {
let temp = DailerLabel.text ?? ""
DailerLabel.text = String(temp.dropLast())
}
}
Here's a better version
#IBAction func backspaceButtonPressed(_ sender: UIButton) {
guard
let text = dialerLabel.text,
!text.isEmpty
else {
return
}
dialerLabel.text = String(text.dropLast())
}

using switch statement inside a button

Please help and I'm sorry if this is covered somewhere else although i have looked elsewhere and whilst there are answers to my topic i cannot find one for my problem. so if anyone could help that would be great.
basically i am trying to do a switch statement inside a button so that when i click the button the statement activates in my label, but for some reason i cannot get it to work
here is my code below
when i hit run it always shows the "This is an even number between 0 and 10" regardless of even number, odd number or large number
Any help would be greatly appreciated
thank you very much
Right before the switch line you have to add three lines to assign the value of the input text field to the variable number.
guard let inputText = numberInput.text, let input = Int(inputText) else {
numberOutput.text = "Please enter a number!"
return }
number = input
This code works fine in playground, always prints expected output.
var number = 6
switch number {
case 0,2,4,6,8,10:
print("even")
case 1,3,5,7,9:
print("odd")
default:
print("higher")
}
where are you changing the number variable? Are you doing it on one of the callback methods for textfield delegate?
you are not changing the value of your var number. Looks like it is always 6 based from your code
You can simply do this:
import UIKit
class EmptyViewController: UIViewController
{
#IBOutlet weak var label: UILabel!
#IBOutlet weak var textField: UITextField!
#IBAction func buttonHit(_ sender: UIButton)
{
if let text = textField.text, let number = Int(text)
{
switch number {
case 0,2,4,6,8,10:
label.text = "Even"
case 1,3,5,7,9:
label.text = "Odd"
default:
label.text = "Higher"
}
}
else
{
label.text = "Please enter a valid number"
}
}
}

UIDatePicker to call specific image in UIImageView

Why is "1925-1-23" and "1924-2-5" being excluded when I try to call an image with them in date picker? I am successfully able to call images with every date in between the two dates above. Why are the dates "1925-1-23" and "1924-2-5" the only dates not calling images.
import UIKit
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs === rhs || lhs.compare(rhs) == .OrderedAscending
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedDescending
}
extension NSDate: Comparable { }
class ViewController: UIViewController {
#IBOutlet weak var displayAnimal: UIImageView!
#IBOutlet weak var dateWheel: UIDatePicker!
#IBAction func goButton(sender: UIDatePicker)
{
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
{
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let rabbit1A = dateStringFormatter.dateFromString("1924-2-5")
let rabbit2A = dateStringFormatter.dateFromString("1925-1-23")
if(dateWheel.date.compare(rabbit1A!) == NSComparisonResult.OrderedDescending &&
dateWheel.date.compare(rabbit2A!) == NSComparisonResult.OrderedAscending)
{
// set the image of UIImageView
displayAnimal.image = UIImage(named: "rabbit")
}
In your IBOutlet:
#IBAction func selectDateButton(sender : UIDatePicker) {
// set the date criteria here
if(sender.date.compare(dateA) == NSComparisonResult.OrderedAscending && sender.date.compare(dateB) == NSComparisonResult.OrderedDescending) {
// set the image of UIImageView
displayAnimal.image = UIImage(named: "rabbit")
}
}
where dateA and dateB are the date (in form of NSDate) that falls into the criteria of displaying rabbit image.
A date picker won't talk to an image view. A date picker is a UIControl.
The logic to do what you want belongs in your view controller.
You would set up an IBOutlet to your date picker.
You'd add an OK button to your view controller in IB that linked to an IBAction method.
In that IBAction method you would look at the date property of the picker (using the picker's outlet.) If the date matches one of your magic dates, you'd have code that would load one of your images into an image view that was linked to another IBOutlet in your view controller.
Break it down into baby steps. Hook up the outlets and actions. At first just put a println("In button action") in your IBAction method. Next, fetch the date from the picker and log that in your IBAction.
Next, figure out how to write a switch statement that matches your different dates and prints statements when you match your different dates. That will require a detour into the docs to read about Swift's very powerful switch statement.
Next figure out how to load your different images from your array of names and install them into an image view on your view controller when you click a button. (First set up an Int instance variable imageIndex that starts at 0, and have a button press load an image name from you array of image names, increment the index for next time, and then installs the loaded image into your image view.
Finally, adjust your switch statement so your various magic dates load the desired image into your image view.