如何区分自定义单元格中的两个textField?

时间:2019-06-11 04:38:22

标签: swift uitableview uitextfield

我在表视图的自定义单元格中有两个textFields(storyTitle和Author),并希望通过textFieldDidEndEditing方法在这些字段中编辑和保留数据。如何区分方法中的两个字段?

我当前的代码如下:

func textFieldDidEndEditing(_ textField: UITextField) {

    let touchPosition:CGPoint = textField.convert(CGPoint.zero, to:self.storiesTableView)

    let indexPath = self.storiesTableView.indexPathForRow(at: touchPosition)

    let storyForEdit = self.stories?[indexPath!.row]

    var editedTitleText = ""

    let cell = tableView(storiesTableView, cellForRowAt: indexPath!) as! StoryCell

    let storyTitleField = cell.storyTitleField


    if textField.text?.isEmpty ?? true {

        deleteTitle(at: storyForEdit!)

    } else {

        editedTitleText = textField.text ?? ""

        do {
            try self.realm.write {
                storyForEdit!.title = editedTitleText
            }
        } catch {
            print("Error editing story \(error)")
        }

        self.storiesTableView.reloadData()


    }
}

我对storyCell.swift中的两个字段都有参考点:

class StoryCell: UITableViewCell {


@IBOutlet weak var storyTitleField: UITextField!

@IBOutlet weak var authorField: UITextField!

....}

但是,当我尝试使用以下代码区分两个字段时,(例如:iphone: uitextfield, multiple textfields with the same delegate?):

    if textField == storyTitleField {

        print("Here we are in storyTitle field")

    }

什么也没发生-没有数据持久化。但是,如果仅使用通用textField,则无法区分标题和作者textField。感谢您对此的任何建议。

2 个答案:

答案 0 :(得分:2)

您可以尝试

override func viewDidLoad() {
        super.viewDidLoad()
        textfield1.delegate = self
        textfield1.tag = 11

        textfield2.delegate = self
        textfield2.tag = 22

        textfield3.delegate = self
        textfield3.tag = 33
}



func textFieldDidEndEditing(_ textField: UITextField) {

        if textField.tag == 11
        {
            //your code here
        }

        if textField.tag == 22
        {
            //your code here
        }

        if textField.tag == 33
        {
            //your code here
        }

    }

答案 1 :(得分:1)

为每个TextField设置一个不同的标签(

txtFld1.tag = 5
txtFld2.tag = 6

),然后在textFieldDidEndEditing中检查textField的标记。