Reputation: 936
I have a basic chat application and I want it so that when inputTextField.text == nil nothing no information gets sent from the textField. The solution I attempted was to disable the button if inputTextField.text == nil but that proved futile. Below is the both the instantiation of the button and the function that handles the send. I have included a screen shot of the build that shows what it looks like when inputTextField.text == nil.
I do not want the chat bubbles to show.
Any suggestions?
lazy var sendButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Send", for: UIControlState())
let titleColor = UIColor(red: 0, green: 137/255, blue: 249/255, alpha: 1)
button.setTitleColor(titleColor, for: UIControlState())
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
button.addTarget(self, action: #selector(handleSend), for: .touchUpInside)
return button
}()
func handleSend(){
print(inputTextField)
let delegate = UIApplication.shared.delegate as! AppDelegate
let context = delegate.managedObjectContext
if inputTextField.text == nil {
sendButton.isEnabled = false
}else{
FriendsController.createMessageWithText(inputTextField.text!, friend: friend!, minutesAgo: 0, context: context, isSender: true)
}
do{
try context.save()
inputTextField.text = nil
}catch let err {
print(err)
}
}
Upvotes: 0
Views: 1151
Reputation: 473
Please set UITextField Delegate method shouldChangeCharactersInRange and you can handle when no text then disable and enable
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
if textField.text?.characters.count == 0{
sendButton.isEnabled = false
}else{
sendButton.isEnabled = true
}
return true
}
I hope it's working for you!.
Upvotes: 0
Reputation: 42
You can check if the textfield is empty on your handleSend() function. This will trim the extra spaces before and after the input string as well
let inputString = inputTextField.text
if(inputString.trimmingCharacters
(in:CharacterSet.whitespacesAndNewlines) ?? "").isEmpty {
print("String is nil or empty")
}else {
//do your code for sending the data
}
Upvotes: 1
Reputation: 4377
If there is no text in the input text field it doesn't mean that is nil , is just blank, you can check for the textfield.text.characters.count and see that is bigger than 0
Upvotes: 0
Reputation: 539
You can achieve that by using sent event Editing Changed
of UITextField
.
@IBAction func textFieldDidChanged(_ sender: UITextField) {
if sender.text == "" {
sendButton.isEnabled = false
} else {
sendButton.isEnabled = true
}
}
Hope this helps.
Upvotes: 0
Reputation: 173
This is not a big deal according to me.You can just check if inputTextField.text == "".And whenever there will be no text then your requirement will be fullfilled. Hope it will help you.
Upvotes: 0