2

This is my very first question on Stack Overflow so I hope I'm following the rules correctly.

I'm making a To-Do list app in Swift and I'm trying to prevent blank or empty spaces from being appended to the table.

My UITextField:

@IBOutlet weak var item: UITextField!

My addItem button:

@IBAction func addItem(sender: AnyObject) {

    if item.text.isEmpty {
    //Do not append item to array
}

Thank you for any help!

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
JohnJLilley
  • 173
  • 1
  • 2
  • 10
  • 1
    Welcome to Stack Overflow! So far your question is good, except you haven't indicated what you expected, what actually happened, and how they differ. That is, what's not working? Can you expand on that? – Aaron Brager Feb 13 '15 at 04:15
  • Currently, even with a blank UITextField, when I click the addItem button, it'll append a blank row to my table. I want it so that when the user clicks the addItem button, it avoids adding that blank row and tells the user to type something. I already have the UILabel set up with a message telling the user, "Please add a task", and fades out over a duration of 3 seconds. It's just the blank space I'm worried about right now. – JohnJLilley Feb 13 '15 at 04:28

2 Answers2

1
let trimmedString = item.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

if countElements(trimmedString) > 0 {
    // append the item
}

The more thorough solution might be to use the UItextFieldDelegate protocol and prevent people from typing blank spaces in the first place. Hard to do camel casing on mobile, so I apologize for typos.

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
Jeremy Pope
  • 3,342
  • 1
  • 16
  • 17
  • You just had 1 small typo (`!` instead of `.`). Just edited it, but not sure if it'll stick since that's technically a rule violation... – Aaron Brager Feb 13 '15 at 04:40
1

You can do this

if item.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) != "" {
    //addNew()
}

stringByTrimmingCharactersInSet : Returns a new string made by removing from both ends of the receiver characters contained in a given character set. The parameter NSCharacterSet.whitespaceCharacterSet removes the whitespace from both ends.

rakeshbs
  • 24,392
  • 7
  • 73
  • 63
  • Thanks for responding. Quick question, where the "//addNew()" is, what shall I add in there? I'm a new developer of two weeks and still trying to grasp Swift concepts! – JohnJLilley Feb 13 '15 at 04:35
  • Addnew is just a comment. You can add your appending code inside the if condition instead of my comment – rakeshbs Feb 13 '15 at 04:37
  • This solved my problem! Thank you for your patience and explaining it to me in detail. – JohnJLilley Feb 13 '15 at 04:40