简体   繁体   中英

Using UITextViews as UITextFields

This is my first question.

I'm currently working on an iOS app in Swift. I was previously using three UITextFields for users to enter their data (it's a journaling app), but I hadn't realized that UITextField was limited to one line.

I've worked on getting three UITextViews to behave like UITextFields, except for one thing. I was using the code below to detect if the user pressed the return key so that they could begin typing in the next TextView (like the way that the return key behaves with multiple TextFields).

My one problem is that when the cursor moves down to the next TextView, it brings the new line ("\\n") with it! I've tried many different ways to fix this and nothing seems to be working. Any ideas?

Thanks, Matt

func textView(textView: UITextView!, shouldChangeTextInRange: NSRange, replacementText: NSString!) {
    if(replacementText == "\n") {
        if(textView == firstTextView) 
        {
            firstTextView.resignFirstResponder()
            secondTextView.becomeFirstResponder()
        }

        if(textView == secondTextView)
        {
            secondTextView.resignFirstResponder()
            thirdTextView.becomeFirstResponder()
        }

        if(textView == thirdTextView)
        {
            thirdTextView.resignFirstResponder()
        }

    }
}

As far as I know, textView(_:shouldChangeTextInRange:replacementText:) must return Bool value :

 optional func textView(_ textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool 

And when you return false , it cancels the change of the text. So I think you should:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    if(replacementText == "\n") {

        // ...

        return false
    }
    return true
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM