如果textfield是myTextField {condition}

时间:2015-10-06 14:49:42

标签: ios swift uitextfield

我们有办法在Swift中做到这一点吗?

var myTextfield: UITextfield

if textfield is myTextField {
   condition
}

我尝试过但失败了:

if UITextfield = myTextField
if textfield = myTextField
if UITextfield.type = myTextField

也试过" =="作为比较运算符。

2 个答案:

答案 0 :(得分:1)

来自Apple Documentation

  

Swift还提供了两个身份运算符(===和!==),你就可以了   用于测试两个对象引用是否都引用相同   对象实例。

答案 1 :(得分:-1)

尝试以下

import UIKit

class ViewController: UIViewController, UITextFieldDelegate{

    //@IBOutlet weak var nameTF: UITextField! { didSet { nameTF.delegate = self } }
    //@IBOutlet weak var nameTF2: UITextField! { didSet { nameTF.delegate = self } }

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

        print("test")



        var myTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 10, width: 200.00, height: 40.00));
        self.view.addSubview(myTextField)
        myTextField.backgroundColor = UIColor.redColor()
        myTextField.text = "some string"
        myTextField.borderStyle = UITextBorderStyle.Line
        myTextField.tag = 1
        myTextField.delegate = self

        var myTextField2: UITextField = UITextField(frame: CGRect(x: 0, y: 200, width: 200.00, height: 40.00));
        self.view.addSubview(myTextField2)
        myTextField2.backgroundColor = UIColor.redColor()
        myTextField2.borderStyle = UITextBorderStyle.Line
        myTextField2.tag = 2
        myTextField2.delegate = self


    }

     func textFieldDidBeginEditing(textField: UITextField) {
        if (textField.tag == 1 ) {
            print("first text field")
        }

        if (textField.tag == 2)
        {
            print("second text field")
        }

    }



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


}