【发布时间】:2019-06-14 06:06:38
【问题描述】:
当我设置自定义 UITableViewCell 时,如何解决无法使用自定义 init 方法的问题?我见过How can I use a custom initializer on a UITableViewCell?,但是,我正在添加我想在init 方法中覆盖的约束。我需要添加一个格式不同的文本字段,例如数字。
我尝试从UITableViewCell 类继承并在init 方法中设置样式枚举,但在调用super.init 之前无法设置。
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 方法,但正如我所说,我宁愿不删除约束和其他部分。
【问题讨论】:
-
您是否尝试过使用便利初始化?
-
单元被重复使用,因此无论如何您都需要重新配置单元约束。您可以在
textFieldStyle属性上使用didSet观察者。 -
感谢@Let's_Create,但我在使用 convince init 时遇到了同样的问题,在超级调用 init 之前仍然无法使用它。
标签: ios swift uitableview cocoa-touch