如何在Swift中转换NSRange为Range<String.Index>?
NSRange
Range<String.Index>
我想使用以下UITextFieldDelegate方法:
UITextFieldDelegate
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool { textField.text.stringByReplacingCharactersInRange(???, withString: string)
的NSString版本(与Swift String相对)replacingCharacters(in: NSRange, with: NSString)接受an NSRange,因此一个简单的解决方案是将其 转换String为NSStringfirst。在Swift3和2中,委托和替换方法的名称略有不同,因此取决于您使用的是哪种Swift:
NSString
replacingCharacters(in: NSRange, with: NSString)
String
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) }
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let nsString = textField.text as NSString? let newString = nsString?.stringByReplacingCharactersInRange(range, withString: string) }