swift - 如何区分自定义单元格中的两个文本字段?

标签 swift uitableview uitextfield

我在 TableView 的自定义单元格中有两个文本字段(故事标题和作者),我想通过 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")

    }

没有任何反应 - 没有数据被持久化。但是,如果我只使用通用文本字段,那么我无法区分标题和作者文本字段。感谢您对此提出任何建议。

最佳答案

你可以试试这个

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
        }

    }

关于swift - 如何区分自定义单元格中的两个文本字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56536571/

相关文章:

swift - 实时发光着色器混淆

ios - 将 View Controller 保持在与左侧相同的位置

ios - cell.detailTextLabel.text 为 NULL

ios - 在ios中从UITableView、Plist生成PDF

ios - 设置文本字段的数值范围

xcode - 改变 alpha 值会改变文本吗?

swift - 协议(protocol)方法中的返回类型协变

ios - SwiftUI : ConfigurationError: noPreviewInfos 中的预览抛出错误

ios - 比较 Swift 中字典的相等性

ios - UITextField shouldChangeCharactersInRange 没有检测到第一个字符