NSRange to Range

前端 未结 13 1227
失恋的感觉
失恋的感觉 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

    I've found the cleanest swift2 only solution is to create a category on NSRange:

    extension NSRange {
        func stringRangeForText(string: String) -> Range {
            let start = string.startIndex.advancedBy(self.location)
            let end = start.advancedBy(self.length)
            return Range(start: start, end: end)
        }
    }
    

    And then call it from for text field delegate function:

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let range = range.stringRangeForText(textField.text)
        let output = textField.text.stringByReplacingCharactersInRange(range, withString: string)
    
        // your code goes here....
    
        return true
    }
    

提交回复
热议问题