我在Swift中定制了一个UITableViewCell类 . 我在这个类中定义了一个textField并为它添加了约束 .
class DBCell: UITableViewCell {
var textField:UITextField?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
textLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
fatalError("init(coder:) has not been implemented")
}
required override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
textLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
}
}
class DBEditCell: DBCell{
required init(coder aDecoder: NSCoder) {
uper.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
if textField == nil
{
textField=UITextField(frame: CGRectZero)
}
textField?.textAlignment=NSTextAlignment.Left
textField?.clearButtonMode=UITextFieldViewMode.WhileEditing
textField?.enabled=true
self.shouldIndentWhileEditing=false
textField?.delegate=self
contentView.addSubview(textField!)
textLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
//Add constraints to textField
let hBinds=NSDictionary(objectsAndKeys:textLabel,"textLabel",textField!,"textField")
textField?.setTranslatesAutoresizingMaskIntoConstraints(false)
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textLabel]-[textField]-|", options: nil, metrics: nil, views: hBinds))
let vBinds=NSDictionary(objectsAndKeys:textField!,"textField")
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[textField]-|", options: nil, metrics: nil, views: vBinds))
}
}
当我从tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath)创建自定义单元格并在UITableView中设置编辑时,它看起来很好 .
但是当我选择一个自定义单元格时,该单元格缩进并且看起来很难看 .
为什么自定义单元格左移和上移?我该如何解决这个问题?任何建议都应该感激 .
今天我为DBCell添加了约束:
let vBinds=NSDictionary(objectsAndKeys:textLabel,"textLabel")
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[textLabel]-|", options: nil, metrics: nil, views: vBinds))
我发现编辑时单元格包含中心,但单元格仍然向左移动 . 我试图向textLabel添加水平约束,如下所示:
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textLabel]-|", options: nil, metrics: nil, views: hBinds))
它没有用 .
1 回答
问题解决了!我已将代码修改为:
现在我没有为textLabel设置任何约束,只为textField设置约束,我得到了正确的对齐textField .