2017-01-20 12 views
1

私はそれの内側にUIButtonsで配列UIStackViewsを作成する機能を持っている:UITableViewCellスィフトの内部でUIStackViewに制約をプログラムで追加する方法はありますか?

func generateStackViews() -> [UIStackView] { 
    var stackViewArray = [UIStackView]() 
    let finalButtonArray = generateButtons() 
    for buttons in finalButtonArray{ 
     stackViewArray.append(createStackView(subViews: buttons)) 
    } 
    return stackViewArray 
} 

私はその後、tableViewCellにその配列を追加します。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "First")! 
    cell.contentView.addSubview(generateStackViews()[indexPath.row]) 
    return cell 
} 

すべてが正常に動作しますが、私は追加しようとすると、制約によって、stackViewsがセルに固定されると、このエラーが発生します。

failure in -[UITableViewCell _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:]

I stackViewscellForRowAt関数を作成する関数に制約を追加しようとしましたが、contentView、セルとtableViewに固定しようとしましたが、どちらもうまく機能せず、同じエラーメッセージが表示されました。

私のロジックはどこに問題がありますか?

答えて

2

このメソッドを呼び出して、プログラムで制約を追加します。

func addSubviewWithConstraint(to parentView: UIView, and childView: UIView, top:CGFloat, bottom:CGFloat, leading:CGFloat, trailing:CGFloat) { 
    parentView.addSubview(childView) 
    //Below line tells the view to not use AutoResizing 
    childView.translatesAutoresizingMaskIntoConstraints = false 
    // set top constraint 
    let topConstraint = NSLayoutConstraint(item: childView, attribute: .top, relatedBy: .equal, toItem: parentView, attribute: .top, multiplier: 1, constant: top) 
    // set Bottom constraint 
    let bottomConstraint = NSLayoutConstraint(item: childView, attribute: .bottom, relatedBy: .equal, toItem: parentView, attribute: .bottom, multiplier: 1, constant: bottom) 
    // set leading constraint 
    let leadingConstraint = NSLayoutConstraint(item: childView, attribute: .leading, relatedBy: .equal, toItem: parentView, attribute: .leading, multiplier: 1, constant: leading) 
    // set Bottom constraint 
    let trailingConstraint = NSLayoutConstraint(item: childView, attribute: .trailing, relatedBy: .equal, toItem: parentView, attribute: .trailing, multiplier: 1, constant: trailing) 
    //Add all constraints to parentView 
    parentView.addConstraint(topConstraint) 
    parentView.addConstraint(bottomConstraint) 
    parentView.addConstraint(leadingConstraint) 
    parentView.addConstraint(trailingConstraint) 
} 

このようにこのメソッドを呼び出します。

self.addSubviewWithConstraint(to: cell.contenetView, and: stackView, top: 0, bottom: 0, leading: 0, trailing: 0) 
+0

ありがとうございました。これは非常に参考になりました。私は初心者ですので、この背後にある論理を説明できれば大いに感謝します –

関連する問題