按下Enter键时获取光标的位置

时间:2019-01-10 08:21:28

标签: iphone swift

我想让用户在编辑模式下按Enter键时拆分UITextField。像这样:

  

foo | bar(竖线为光标)-现在我按Enter

,我想在下面创建新的UITextField,它应该像这样:

  

foo

     

但是按Enter键时我无法获得光标的位置。我尝试了以下代码段:

 override func viewDidLayoutSubviews() {

    spanishButtonCenter = spanishButton.center
    italianButtonCenter = italianButton.center
    frenchButtonCenter = frenchButton.center
    germanButtonCenter = germanButton.center

    spanishButton.center = playButton.center
    italianButton.center = playButton.center
    frenchButton.center = playButton.center
    germanButton.center = playButton.center
}

@IBAction func playClicked(_ sender: UIButton) {

    if playButton.currentImage == UIImage(named: "play_button") {
        UIView.animate(withDuration: 0.8, animations: {
            self.spanishButton.alpha = 1
            self.italianButton.alpha = 1
            self.frenchButton.alpha = 1
            self.germanButton.alpha = 1


            self.spanishButton.center = self.spanishButtonCenter
            self.italianButton.center = self.italianButtonCenter
            self.frenchButton.center = self.frenchButtonCenter
            self.germanButton.center = self.germanButtonCenter


        })
    }
    //playButton.setImage(UIImage(named: "play_clicked"), for: .normal)
}

但是它返回 if let selectedRange = field.selectedTextRange { let cursorPosition = field.offset(from: field.beginningOfDocument, to: selectedRange.start) print("\(cursorPosition)") } 而不是6。似乎按Enter键会使光标首先跳到当前单词的末尾,然后执行我的代码段。我试图将其放在3textFieldShouldReturn以及UITextField textFieldShouldEndEditing中,结果也相同。

是否有防止光标跳转的方法,或者有其他解决方法?我是iPhone开发的初学者,所以我可能缺少明显的东西...

0 个答案:

没有答案