2017-03-28 6 views
1

UITableViewCell's contentView에 제약 조건을 프로그래밍 방식으로 추가하려고 할 때 문제가 있습니다.UITableViewCell : UITextView에서 콘텐츠 뷰로 프로그래밍 방식으로 제약 조건 추가?

cellForRowAt에서 프로그래밍 방식으로 UITextView을 만든 다음 제약 조건을 적용하고이를 셀의 contentView에 추가하려고합니다.

The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x1700951d0 UITableViewCellContentView:0x12de3e150.leading == UITextView:0x12e891400.leading + 8 (inactive)> 
    When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. 

내 다음 코드 : 이에 대해

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{ 
    // Dequeue the cell to load data 
    let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 

    if indexPath.section == 1 
    {    
     let textView: UITextView = UITextView() 

     textView.textColor = UIColor.black 
     textView.translatesAutoresizingMaskIntoConstraints = false 

     cell.addSubview(textView) 

     let leadingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: textView, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 8.0) 

     let trailingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: textView, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: -8.0) 

     cell.contentView.addConstraint(leadingConstraint) 
     cell.contentView.addConstraint(trailingConstraint) 

     let topConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: textView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0) 

     let bottomConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: textView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0) 

     cell.contentView.addConstraint(topConstraint) 
     cell.contentView.addConstraint(bottomConstraint) 
    } 

    return cell 
} 

내가 언급 한 오류에 관한 질문을 많이 참조 할 수 있지만, 발견되지 않은 한 임 충돌과 오류가 발생하지만

, UITableViewCell에 적용하면 오류가 발생합니다.

누군가 나를 올바른 방향으로 안내 할 수 있습니까?

감사합니다.

답변

2

텍스트보기에 cell.contentView (NOT )을 추가하십시오. 그래서 cell.contentView.addSubview(textView)으로 바꾸면 효과가 있습니다!

+0

바보! 어떻게 내가 놓칠 수 있었는지 ... 셀의 'contentView'에 제약 조건을 추가했지만'cell' .....에'textView'를 추가했습니다. :) – Pangu

+0

예, 언젠가 저는 그 상황에서. 하하 : D –

관련 문제