首页 > 解决方案 > 如何创建包含 UITextField 子类的自定义 TextCell 和 TextRow?

问题描述

我正在使用Eureka FormsSearchTextField

在我的表单中,我希望有一些与 (Eureka) 内置的非常相似的东西TextRow。不同之处在于此自定义TextRow将使用 aSearchTextField而不是常规的UITextField

我首先认为我可以复制所有与类相关的代码TextRowTextCell稍微重命名这些类。但是,我发现代码_FieldRow很难理解,而且我不知道应该复制什么代码。

然后我看到我可以设置cellProvider属性以提供自定义单元格:

<<< TextRow() {
    $0.cellProvider = CellProvider<TextCell>(nibName: "NewCustomCell", bundle: .main)
    $0.title = "TextRow"
}

所以我想我只需要一个xib文件。我试图找到 Eureka 使用的 xib 文件,TextCell以便我可以复制它并稍微编辑它,但我在目录下找不到单个 xib 文件Pods/Eureka。然后我尝试制作自己的xib文件。

添加表格视图单元格后,我将其类设置为,TextCell因为我需要一个CellProvider<TextCell>. 然后我尝试将文本字段和标签连接到IBOutlets in _FieldCell(这是我应该做的,对吗?)但插座只是没有出现。我将课程更改为_FieldCell并且他们正确显示,但是我不能将带有 a 的笔尖传递_FieldCell到 a CellProvider<TextCell>,可以吗?

重申我的目标:创建一个表单单元格,其中有一个SearchTextField作为文本字段并且行为与TextCell其他所有内容相同。

标签: iosswifteureka-forms

解决方案


您需要使用自定义行和单元格.. 像这样

class _SearchTextFieldCell<T>: _FieldCell<T> where T: Equatable, T: InputTypeInitiable {

    required init(style: UITableViewCellStyle, reuseIdentifier: String?) {

        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.textField.removeFromSuperview()

        let searchTextField = SearchTextField()
        searchTextField.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(searchTextField)
        self.textField = searchTextField
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class SearchTextCell: _SearchTextFieldCell<String>, CellType {

    required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    open override func setup() {
        super.setup()
    }
}

class _SearchTextRow: FieldRow<SearchTextCell> {

    public required init(tag: String?) {
        super.init(tag: tag)
    }
}

final class SearchTextRow: _SearchTextRow, RowType {

    required public init(tag: String?) {
        super.init(tag: tag)
    }
}

然后你可以使用自定义行

<<< SearchTextRow() {

    $0.title = "Search"

    guard let tf = $0.cell.textField as? SearchTextField else {
        return
    }

    tf.filterStrings(["lorem", "ipsum", "dolor", "sit", "amet"])
}

推荐阅读