当我设置自定义 UITableViewCell
时,如何解决无法使用自定义 init
方法的问题?我看过How can I use a custom initializer on a UITableViewCell? ,但是,我添加了我想在我的 init
方法中覆盖的约束。我需要添加一个格式不同的文本字段,例如数字。
我已经尝试继承我的 UITableViewCell
类并在我的 init
方法中设置样式枚举,但我无法在调用 super 之前设置它。初始化
。
class LabelIntegerTextfieldTableViewCell: LabelTextfieldTableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)
{
super.textFieldStyle = .Integer
// 'self' used in property access 'textFieldStyle' before 'super.init' call
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
open class LabelTextfieldTableViewCell: UITableViewCell
{
public var label = UILabel()
public var textField = UITextField()
public var textFieldStyle = eTextfieldStyle.Integer
override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
switch textFieldStyle
{
case .Integer:
textField.contentVerticalAlignment = .center
textField.textAlignment = .right
textField.keyboardType = .numberPad
// snip
if (textFieldStyle == .MediumText)
{
contentView.addConstraints(NSLayoutConstraint
.constraints(withVisualFormat:
"H:|-[label]-[textField(==label)]-|",
options: [], metrics: nil, views: viewsDict))
}
else
{
contentView.addConstraints(NSLayoutConstraint
.constraints(withVisualFormat:
"H:|-[label]-[textField(100)]-|",
options: [], metrics: nil, views: viewsDict))
}
我知道在其他 SO 帖子中它提到使用 update
方法,但正如我所说,我宁愿不删除约束和其他部分。
最佳答案
您尝试实现的行为实际上并不是一个好的设计,因为 UITableViewCell
被重用了。所以你不应该依赖于配置它们出现在 init
方法中。例如,您可以实例化一个传递 Integer
样式的单元格,稍后,如果您将单元格设置为具有不同的样式,则会出现不一致的状态(因为您将看到的不会反射(reflect)出什么你设置)。话虽这么说,您应该考虑使用更具 react 性的方法,在这种方法中,您的单元格会根据设置的内容,无论何时设置。在您的情况下,您可能想查看 didSet
属性观察器。你会有类似下面的东西:
public var textFieldStyle = eTextfieldStyle.Integer {
didSet {
updateAppearance()
}
}
func updateAppearance() {
switch textFieldStyle {
case .Integer:
// ...
}
}
编辑
并且在您的 tableView(_:cellForRowAt:)
中,您只需要设置适当的样式,如下所示:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "your cell identifier goes here", for: indexPath)
// Here you obtain the proper style depending on the index path, for instance:
if indexPath.row == 0 {
cell.textFieldStyle = .Integer
} else {
cell.textFieldStyle = . MediumText
}
return cell
}
关于ios - 在使用自定义 UITableViewCell 时解决没有自定义 init 方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54279998/