ios - 解决使用自定义 UITableViewCell 时没有自定义 init 方法的问题
问题描述
init
设置自定义方法时如何解决无法使用自定义方法的问题UITableViewCell
?我已经看到如何在 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
方法,但正如我所说,我宁愿不删除约束和其他部分。
解决方案
您试图实现的行为实际上并不是一个好的设计,因为UITableViewCell
s 被重用了。所以你不应该依赖于在init
方法中配置它们的外观。例如,您可以实例化一个单元格传递Integer
样式,然后,如果您将单元格设置为具有不同的样式,您将有一个不一致的状态(因为您将看到的内容不会反映您设置的内容)。话虽如此,您应该考虑使用更具反应性的方法,您的单元格的行为根据设置的内容,无论何时设置。在你的情况下,你可能想看看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
}
推荐阅读
- xml - REST 响应回归测试 - 需要高级比较
- c++ - 为什么要使用 Dereference 运算符来声明指针?
- java - 我有一个检测脏话的我的世界插件。玩家诅咒时如何执行命令?
- graphql - GraphQL 使用来自返回结果集的动态 ID 来呈现正确的数据集
- typescript - 仅将可区分联合类型限制为当前属性
- android - 颤振 | showModalBottomSheet 基于键盘高度的底部填充,但动画很慢
- android - 如何让服务器主动通知客户端资源变化?
- sql - SQL 来识别某些列与过滤器不同的 ID
- android - 有没有办法在明暗模式之间切换后保留变量状态的值以显示在文本视图中
- java - 调用 MediaProjection.createVirtualDisplay 时无法启动已经启动的 MediaProjection 并且很少出现 NullPointerException