添加Leading Constraint以动态添加UITableViewCell

时间:2017-06-21 11:39:02

标签: ios swift uitableview tableviewcell

我想为动态添加的表视图单元格添加约束。

创建单元格的当前代码是:

// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return createTableRow()

}

 func createTableRow() -> UITableViewCell{

    let cell:CustomTableViewCell = self.extraGuestsTable.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell! as! CustomTableViewCell

//        let newTrailingConstraint = NSLayoutConstraint(item: cell, attribute: .leading, relatedBy: .equal, toItem: extraGuestsTable, attribute: .trailing, multiplier: 1, constant: 50)
//        cell.addConstraint(newTrailingConstraint)

    let widthConstraint = cell.widthAnchor.constraint(equalToConstant: 600.0)
//        let heightConstraint = someView.heightAnchor.constraint(equalToConstant: 50.0)
    let leadingConstraint = cell.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 50.0)


    NSLayoutConstraint.activate([widthConstraint,leadingConstraint])


    let h = cell.frame.size.height
    let w = cell.frame.size.width



    let tf = UITextField(frame: CGRect(x: 0, y: 0, width: w, height: h))
    tf.borderStyle = UITextBorderStyle.roundedRect
    tf.contentVerticalAlignment = UIControlContentVerticalAlignment.center
    tf.placeholder = "Enter text here"

    cell.addSubview(tf)

    return cell
}

我尝试了两种添加前导约束的方法,但它要么a)什么都不做,要么b)使应用程序崩溃并出现以下错误

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <NSLayoutXAxisAnchor:0x61000107eac0 "White_Rose.CustomTableViewCell:0x7f8c6a864e00'cell'.leading"> and <NSLayoutXAxisAnchor:0x600000865cc0 "UIView:0x7f8c6cb167b0.leading"> because they have no common ancestor.  Does the constraint or its anchors reference items in different view hierarchies?  That's illegal.'

有没有更好的方法为动态UITableViewCell添加约束?

0 个答案:

没有答案