Getting autocomplete to work in swift

前端 未结 12 553
清酒与你
清酒与你 2020-12-04 15:55

I am trying to implement autocompletion, but can\'t find an example that works in Swift. Below, I\'m tring to convert Ray Wenderlich\'s autocompletion tutorial and example c

12条回答
  •  情书的邮戳
    2020-12-04 16:43

    Here's a way to add multiple tags based on "#" being typed in like twitter.

    Variable typedSubstring is the global substring.

      func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
    
    autocompleteTableView!.hidden = false
    var changedText = (self.textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
    var items = changedText.componentsSeparatedByString("#")
    
    if (items.count > 0) {
      typedSubstring  = "#" + items.lastObject as NSString
    
      self.searchAutocompleteEntriesWithSubstring(typedSubstring)
    }
    
    return true
    

    }

    Improved on DrWhat's solution so that when you select a cell, it appends it correctly after where the user has already typed in.

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 
    let selectedCell : UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
    
    let selectedText = selectedCell.textLabel?.text as String!
    
    // Remove what has been typed already
    let trimmedString = selectedText.stringByReplacingOccurrencesOfString(typedSubstring, withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
    
    var currentTextField = textField.text
    
    // then append to what has been typed
    textField.text = currentTextField + trimmedString
    

提交回复
热议问题