I have customized a UITableViewCell class in Swift.I defined a textField in this class and added constraints to it.
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))
}
}
When I created custom cell from tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) and set editing in UITableView,it looks well. But when I selected a custom cell,that cell outdented and looks ugly. Why custom cell moved left and upper? How can I resolved this problem? Any advice should be appreciated.
Today I have added constraint to DBCell :
let vBinds=NSDictionary(objectsAndKeys:textLabel,"textLabel")
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[textLabel]-|", options: nil, metrics: nil, views: vBinds))
And I found that the cell contain center when is editing,but the cell still move to left.I have tried to add horizontal constraint to textLabel like this:
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textLabel]-|", options: nil, metrics: nil, views: hBinds))
And it didn't work.