1

Okay the Xcode 7 GM is out and of course that means I have perfectly good swift 2.0 code from last week that doesn't work today. I'm converting a range passed into a textfield delegate method to a swift range and I'm stuck. Any help would be appreciated. So far I understand that the Global advance() method is gone and we should be using the new extension method advancedBY instead but I'm not sure how that fits into this situation. Here is my code that worked yesterday.....

    // MARK: - Textfield Delegate
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    // Convert the NSRange into a Swift Range
    let start = advance(textField.text!.startIndex, range.location)
    let end = advancedBy(range.length)
    let swiftRange = Range<String.Index>(start: start, end: end)

    let text = textField.text!.stringByReplacingCharactersInRange(swiftRange, withString: string)
    // Rest of the method here
}
vichudson1
  • 881
  • 1
  • 10
  • 21

2 Answers2

2

I found the better solution was to just cast the textfield text like this...

    // MARK: - Textfield Delegate
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    let text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
    // rest of method here
}

Found here - Selected answer to "NSRange to Range"

Community
  • 1
  • 1
vichudson1
  • 881
  • 1
  • 10
  • 21
0

The following is worked for me:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let currentText = textField.text ?? ""
    let prospectiveText = (currentText as NSString).stringByReplacingCharactersInRange(range, withString: string)
    print("prospectiveText", prospectiveText)
    return true;
}
Ashok
  • 5,585
  • 5
  • 52
  • 80