iOS快速代理在uiview中有超过1个uitextfield

时间:2015-06-03 20:58:08

标签: ios swift uitextfielddelegate

我有一个iOS应用,一个UIView和三个UITextField(超过1个) 我想了解我的ViewController类管理UITextField的最佳实践。

- 类MainViewController:UIViewController, UITextFieldDelegate

我想知道,因为我有多个UITextField而且只有一个func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool

4 个答案:

答案 0 :(得分:12)

最简单的方法是知道在委托方法中使用哪个文本字段。即你有3个文本字段:field1,field2,field3,当调用委托你可以检测到该做什么:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField == field1 {
        // do something
    } else if textField == field2 {
        // do something
    } else if textField == field3 {
        // do something
    }
  return true
}

不要忘记将所有字段的委托作为自己:field1.delegate = self等。

在你的情况下它会正常工作。

如果你想知道一个更好的解决方案,如果你有更多的字段(10,20?),请告诉我,我会更新我的答案。

答案 1 :(得分:0)

最好的方法是使用tag属性。

Apple Docs上看到:

- (void)textFieldDidEndEditing:(UITextField *)textField {

    switch (textField.tag) {
        case NameFieldTag:
            // do something with this text field
            break;
        case EmailFieldTag:
             // do something with this text field
            break;
        // remainder of switch statement....
    }
}

enum {
    NameFieldTag = 0,
    EmailFieldTag,
    DOBFieldTag,
    SSNFieldTag
};

答案 2 :(得分:0)

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    switch textField {
    case field1:
       // do something 
    case field2:
       // do something 
    case field3:
       // do something 
    }
  return true
}

答案 3 :(得分:0)

这对我有用

import UIKit

class WeatherViewController: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var conditionImageView: UIImageView!
    @IBOutlet weak var temperatureLabel: UILabel!
    @IBOutlet weak var cityLabel: UILabel!
    
    @IBOutlet weak var searchInputField: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.searchInputField.delegate=self
        // Do any additional setup after loading the view.
    }

    @IBAction func searchButtonClicked(_ sender: UIButton) {
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == searchInputField {
            print("Changes done in searchTextField")
        }
        searchInputField.resignFirstResponder() // it hides the keyboard
           performAction()
           print(" Inside textFieldShouldReturn")
           return true
       }
       
      
       func performAction() {
         print(" Perform action called")
           
       }
    
}