NSRange to Range

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

    The NSString version (as opposed to Swift String) of replacingCharacters(in: NSRange, with: NSString) accepts an NSRange, so one simple solution is to convert String to NSString first. The delegate and replacement method names are slightly different in Swift 3 and 2, so depending on which Swift you're using:

    Swift 3.0

    func textField(_ textField: UITextField,
                   shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
    
      let nsString = textField.text as NSString?
      let newString = nsString?.replacingCharacters(in: range, with: string)
    }
    

    Swift 2.x

    func textField(textField: UITextField,
                   shouldChangeCharactersInRange range: NSRange,
                   replacementString string: String) -> Bool {
    
        let nsString = textField.text as NSString?
        let newString = nsString?.stringByReplacingCharactersInRange(range, withString: string)
    }
    
    0 讨论(0)
提交回复
热议问题