选择刚刚使用replaceRange更新的文本(范围:UITextRange,withText:String)

时间:2016-06-04 21:07:06

标签: xcode swift2 uitextview

我正在使用以下代码更改UITextView的内容:

mainTextField.replaceRange((theRange), withText: newStr)

然后我想选择新文本。我正在尝试使用以下代码:

mainTextField.becomeFirstResponder()

let startPosition = mainTextField.positionFromPosition(mainTextField.beginningOfDocument, inDirection: UITextLayoutDirection.Right, offset: startingPoint)
let endPosition = mainTextField.positionFromPosition(mainTextField.beginningOfDocument, inDirection: UITextLayoutDirection.Right, offset: endingPoint)

 if startPosition != nil && endPosition != nil {
    mainTextField.selectedTextRange = mainTextField.textRangeFromPosition(startPosition!, toPosition: endPosition!)
 }

问题是我不知道如何获取startingPoint和endingPoint值。是否有可能从 replaceRange(范围:UITextRange,withText:String)语句中以某种方式获取它们?

编辑: 试着澄清我的问题:

// mainTextField content = "Have a good day"
// mainTextField selected text = "good"

mainTextField.replaceRange((theRange), withText: "happy")
// here theRange refers the selected text "good" not the new one "happy"

如何选择新文字(“快乐”)?

1 个答案:

答案 0 :(得分:1)

您只需使用字符串的长度来确定选择的UITextRange。例如:

extension UITextView // I created this become sometimes it's nice to work with NSRange rather than UITextRange but it's not necessary for your problem.
{
    func textRangeFromNSRange(range:NSRange) -> UITextRange?
    {
        let beginning = self.beginningOfDocument
        guard let start = self.positionFromPosition(beginning, offset: range.location), end = self.positionFromPosition(start, offset: range.length) else { return nil}

        return self.textRangeFromPosition(start, toPosition: end)
    }
}

class ViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!

    override func viewDidAppear(animated: Bool) {
            super.viewDidAppear(animated)
            self.textView.selectable = true
            self.textView.text = "the quick brown fox jumped over the lazy dog"
            let range = self.textView.textRangeFromNSRange(NSRange(location: 0, length: 3))!
            let text = "how now brown cow"
            self.textView.replaceRange(range, withText: text)
            self.textView.selectedTextRange = textView.textRangeFromPosition(range.start, toPosition: textView.positionFromPosition(range.start, offset: text.characters.count)!) //should probably break this into multiple lines for better readability
            self.textView.becomeFirstResponder()


           }
}

在上面的例子中,“the”将被替换为“how now brown cow”和“how now brown cow”将被选中。我正在使用便利功能将NSRange转换为UITextRange。范围将从索引0开始,变为3个字符(“the”)。我用字符串“how now brown cow”替换它。然后我使用前面的UITextRange和我的替换字符串来构造一个新的UITextRangetextView.textRangeFromPosition(range.start, toPosition: textView.positionFromPosition(range.start, offset: text.characters.count)!))。然后我设置为textView的selectedTextRange。您应该确保UITextView可以选择,然后拨打becomeFirstResponder on your UITextView`。