【问题标题】:how to segue a textfield on the same view controller (swift 3)如何在同一个视图控制器上分割文本字段(swift 3)
【发布时间】:2017-04-07 18:34:08
【问题描述】:

我有 2 个文本字段。我希望在文本字段 a 中输入的内容显示在文本字段 b 中。但是 textfield b 仅用于显示。用户只能在文本字段 a 中输入名称。用户在文本字段 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

【问题讨论】:

    标签: ios uiviewcontroller swift3 uitextfield segue


    【解决方案1】:
    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
      }
    
    }
    

    不要忘记连接 TextFields 以从情节提要或 nib 进行委托

    【讨论】:

    • 我怎么能写一个函数把它放在视图中确实加载不需要按下按钮。函数 a 中的任何内容都会自动显示在函数 b 中。
    • 我没有完全理解你的问题,但你可以轻松地在函数之间传递数据
    【解决方案2】:

    您可以使用文本字段的委托方法,例如“textfieldEndEditing”或“textfieldShouldChangeCharacterinrange”,在此委托方法中您可以设置文本字段的文本 b。第二件事,如果您只想显示文本,那么您也可以使用 uilable 代替 textfield b!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      相关资源
      最近更新 更多