简体   繁体   English

如何在同一视图控制器上选择文本字段(Swift 3)

[英]how to segue a textfield on the same view controller (swift 3)

I have 2 textfields. 我有2个文本字段。 I would like what ever is entered in textfield a to be displayed in textfield b. 我希望在文本字段a中输入的内容都可以在文本字段b中显示。 However textfield b is used just for display. 但是,文本字段b仅用于显示。 The user can only enter a name in textfield a. 用户只能在文本字段a中输入名称。 The user enters a name in textfield a and it will be displayed in textfield b. 用户在文本字段a中输入名称,该名称将显示在文本字段b中。

    import UIKit

class ViewController: UIViewController {

@IBOutlet var a: UITextField!
@IBOutlet var b: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    b.isEnabled = false



}

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

enter image description here 在此处输入图片说明

You can use textfield's delegate methods like "textfieldEndEditing" or "textfieldShouldChangeCharacterinrange" and in this delegate method you can set text of your textfield b. 您可以使用文本字段的委托方法,例如“ textfieldEndEditing”或“ textfieldShouldChangeCharacterinrange”,在此委托方法中,您可以设置文本字段b的文本。 Second thing if you just want to display text then you can use uilable also instead of textfield b! 第二件事,如果您只想显示文本,则可以使用uilable代替文本字段b!

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var a: UITextField!
@IBOutlet weak var b: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    b.isEnabled = false
}

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


}

// use extensions your code will be clear always 
// UITextfield delegate
extension ViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
    // if you have many textfields and the user dismissed the keyboard or tapped any other textfield
    if textField === a {
        b.text = textField.text
    }
}

// if the user clicked the return key in keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    // this works if you have only a and b textfields
    // b.text = textField.text

    // use this if statment if you have many text fields
    if textField === a {
        b.text = textField.text
    }
    return true
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // if you want to see your text changes live as soon as the user clicks any button
    b.text = textField.text

    return true
  }

}

Don't forget to connect TextFields to delegate from storyboard or nib whatever your using 别忘了连接TextFields来从情节提要或nib委托,无论您使用什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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