加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Swift中使用stringByReplacingCharactersInRange

发布时间:2020-12-14 05:42:45 所属栏目:百科 来源:网络整理
导读:我试图在Swift / Xcode6中使用UITextFieldDelegate,我正在努力使用我应该使用stringByReplacingCharactersInRange的方式.编译器错误是’无法将表达式的类型’String’转换为类型’$T8′. func textField(textField: UITextField!,shouldChangeCharactersInRa
我试图在Swift / Xcode6中使用UITextFieldDelegate,我正在努力使用我应该使用stringByReplacingCharactersInRange的方式.编译器错误是’无法将表达式的类型’String’转换为类型’$T8′.
func textField(textField: UITextField!,shouldChangeCharactersInRange range: NSRange,replacementString string: String!) -> Bool
{
    let s = textField.text.stringByReplacingCharactersInRange(range:range,withString:string)
    if countElements(s) > 0 {

    } else {

    }
    return true
}

更新Xcode 6 Beta 5:事情是shouldChangeCharactersInRange给出一个NSRange对象,我们需要一个Swift Range对象为stringByReplacingCharactersInRange.这可能还是一个bug,因为我不明白为什么我们还应该处理NS *对象?代表方法的String参数是Swift类型.

以下是各种Swift版本中计算结果字符串的方法.

请注意,所有方法都以完全相同的方式使用 – [NSString stringByReplacingOccurrencesOfString:withString:],语法不同.

这是计算结果字符串的首选方法.转换为Swift范围并在Swift字符串上使用它是容易出错的.例如,Johan的答案在使用非ASCII字符串时以几种方式是不正确的.

Swift 3:

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

Swift 2.1:

func textField(textField: UITextField,replacementString string: String) -> Bool {
    let result = (textField.text as NSString?)?.stringByReplacingCharactersInRange(range,withString: string)
    // ... do something with `result`
}

Swift 1(仅供参考):

let result = textField.text.bridgeToObjectiveC().stringByReplacingCharactersInRange(range,withString:string)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读