NSRange to Range

前端 未结 13 1345
失恋的感觉
失恋的感觉 2020-11-22 11:59

How can I convert NSRange to Range in Swift?

I want to use the following UITextFieldDelegate method:

13条回答
  •  無奈伤痛
    2020-11-22 12:38

    You need to use Range instead of the classic NSRange. The way I do it (maybe there is a better way) is by taking the string's String.Index a moving it with advance.

    I don't know what range you are trying to replace, but let's pretend you want to replace the first 2 characters.

    var start = textField.text.startIndex // Start at the string's start index
    var end = advance(textField.text.startIndex, 2) // Take start index and advance 2 characters forward
    var range: Range = Range(start: start,end: end)
    
    textField.text.stringByReplacingCharactersInRange(range, withString: string)
    

提交回复
热议问题