2015-10-06 18 views
0

我們可以在Swift中做到這一點嗎?如果textfield是myTextField {condition}

var myTextfield: UITextfield 

if textfield is myTextField { 
    condition 
} 

我曾嘗試和失敗:

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

而且試圖 「==」 的比較操作。

+0

爲什麼'if textField === myTextField'? – rmaddy

回答

-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. 
    } 


} 
1

Apple Documentation

雨燕還提供了兩個身份操作符(!===和==),其中 您使用來測試是否兩個對象的引用都參考相同的 對象實例。