Using stringByReplacingCharactersInRange in Swift

2020-02-10 02:17发布

I'm trying to use UITextFieldDelegate in Swift/Xcode6 and I'm struggling with the way I'm supposed to use stringByReplacingCharactersInRange. The compiler error is 'Cannot convert the expression's type 'String' to type '$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
}

Update for Xcode 6 Beta 5: The thing is shouldChangeCharactersInRange gives an NSRange object and we'd need a Swift Range object for stringByReplacingCharactersInRange. Can this still be considered a bug as I don't see why we should still be dealing with NS* objects? The String argument of the delegate method is anyway of a Swift type.

标签: swift
13条回答
仙女界的扛把子
2楼-- · 2020-02-10 03:10
import UIKit

class LoginViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var submitButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let length = count(textField.text) - range.length + count(string)
        if length > 0 {
            submitButton.enabled = true
        } else {
            submitButton.enabled = false
        }
        return true
    }
}
查看更多
We Are One
3楼-- · 2020-02-10 03:12
let newString = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)

bridgeToObjectiveC can be removed in coming updates

查看更多
够拽才男人
4楼-- · 2020-02-10 03:14

The simplest solution I have found is using as NSString - that enables us to use NSRange.

var textField : UITextField = UITextField()
textField.text = "this is a test"

let nsRange : NSRange = NSRange(location: 0, length: 4)

let replaced = (textField.text as NSString)
               .stringByReplacingCharactersInRange(nsRange, withString: "that");

NSLog("Replaced: %@", replaced); //prints "that is a test"
查看更多
戒情不戒烟
5楼-- · 2020-02-10 03:15

Swift 4:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    var text = textField.text ?? ""
    text.replaceSubrange(range.toRange(string: text), with: string)
    ...
    return true
}

extension NSRange {

    /// Convert to Range for given string
    ///
    /// - Parameter string: the string
    /// - Returns: range
    func toRange(string: String) -> Range<String.Index> {
        let range = string.index(string.startIndex, offsetBy: self.lowerBound)..<string.index(string.startIndex, offsetBy: self.upperBound)
        return range
    }
}
查看更多
Juvenile、少年°
6楼-- · 2020-02-10 03:16

With Swift 2.0, the answer from Durul must be changed because characters.count must be used instead of count().

The following must be done.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let length = textField.text!.characters.count - range.length + string.characters.count
    if length > 0 {
        submitButton.enabled = true
    } else {
        submitButton.enabled = false
    }
    return true
}
查看更多
甜甜的少女心
7楼-- · 2020-02-10 03:17

Creating String.Index is cumbersome.

let string = "hello"
let range = string.startIndex .. string.startIndex.succ().succ()
let result = string.stringByReplacingCharactersInRange(range, withString: "si")
查看更多
登录 后发表回答