一尘不染

NSR范围

swift

如何在Swift中转换NSRangeRange<String.Index>

我想使用以下UITextFieldDelegate方法:

    func textField(textField: UITextField!,
        shouldChangeCharactersInRange range: NSRange,
        replacementString string: String!) -> Bool {

textField.text.stringByReplacingCharactersInRange(???, withString: string)

在此处输入图片说明


阅读 255

收藏
2020-07-07

共1个答案

一尘不染

NSString版本(与Swift String相对)replacingCharacters(in: NSRange, with: NSString)接受an NSRange,因此一个简单的解决方案是将其 转换StringNSStringfirst。在Swift3和2中,委托和替换方法的名称略有不同,因此取决于您使用的是哪种Swift:

UITextField3.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)
}

UITextField2.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)
}
2020-07-07