简体   繁体   English

iOS Swift使用for循环在TableView单元格中添加两个视图

[英]iOS Swift Add Two View in TableView Cell with for loop

i recently work on new project and I need to add Two Custom view in one Cell in TableViewController. 我最近在新项目上工作,我需要在TableViewController的一个单元格中添加两个自定义视图。 like this: 像这样:

if indexPath.row == 4 {

        for index in 0..<2 {

            let reviewView = ReviewView()
            reviewView.translatesAutoresizingMaskIntoConstraints = false


            cell.addSubview(reviewView)
            cell.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[v0]-|",options: [],metrics: nil,views: ["v0" : reviewView]))

            if index == 0 {

                cell.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[v0(71)]",options: [],metrics: nil,views:["v0" : reviewView]))
                reviewView.backgroundColor = UIColor.redColor()
                reviewView.frame = CGRectMake(0, 0, cell.contentView.frame.size.width, 71)
            }
            if index == 1 {
                cell.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(71)]-|",options: [],metrics: nil,views:["v0" : reviewView]))
                reviewView.backgroundColor = UIColor.blueColor()
                reviewView.frame = CGRectMake(0, 71, cell.contentView.frame.size.width, 71)
            }


            print(index)
        }

        return cell

    }

but the result is like this(height of both view must be equal and 71) : 但是结果是这样的(两个视图的高度必须等于71):

Simulator Result 模拟器结果

I guess the problem is about Constraint between two view.How I manage that? 我猜问题出在两个视图之间的约束上,我该如何处理?

Thanks guys 多谢你们

EDIT: cell height is auto (UITableViewAutomaticDimension) 编辑:单元格高度是自动的(UITableViewAutomaticDimension)

将约束添加到单元的contentView而不是直接添加到单元

Check out the frame X position 检查框架X的位置

I think there you have problem 我觉得你有问题

reviewView.frame = CGRectMake(0, 71, cell.contentView.frame.size.width, 71) reviewView.frame = CGRectMake(0,71,cell.contentView.frame.size.width,71)

Change 更改

reviewView.frame = CGRectMake(200, 0, cell.contentView.frame.size.width, 71) reviewView.frame = CGRectMake(200,0,cell.contentView.frame.size.width,71)

Take custom UITableViewCell instead of doing programmatically. 使用自定义UITableViewCell而不是通过编程来完成。 In a custom UITableViewCell, you can give constraints directly in storyboard file. 在自定义UITableViewCell中,可以直接在情节提要文件中提供约束。

You're correct that you need constraints between the two subviews. 您是正确的,您需要在两个子视图之间进行约束。

Using auto layout to determine the height of a view requires there to be a clear chain of constraints between the top and bottom of the view. 使用自动布局确定视图的高度要求在视图的顶部和底部之间有清晰的约束链。 This can be as simple as a single height constraint on a view to a series of constraints between subviews. 这可以像视图上的单个高度约束到子视图之间的一系列约束一样简单。

This is your current chain of constraints from top to bottom on the contentView of your cell: 这是您当前在单元格的contentView中从上到下的约束链:

|-[v0] : This is constraining the first view's .Top to the .Top of the contentView |-[v0] :这将第一个视图的.Top限制为contentView.Top

[v0(71)] : This is telling the view to have a height of 71 (or another way to think about it is that it's telling that view's .Bottom to be 71 points down from it's .Top [v0(71)] :这是告诉认为有高度71 (或另一种方式来思考它是,它告诉该视图的.Bottom71分的情况下,从它的.Top

[v0(71)] (second loop) : This is telling the second view to have a height of 71 , similar to the first [v0(71)] (第二个循环):这是告诉第二个视图具有71的高度,类似于第一个视图

[v0]-| : This constrains the second view's .Bottom to the .Bottom of the contentView :这将第二个视图的.Bottom .BottomcontentView.Bottom

The missing piece is between the first view's .Bottom and the second view's .Top . 缺少的部分在第一个视图的.Bottom和第二个视图的.Top

The easiest way to fix this with your current code would be to keep track of the first view and keep a constraint between it's .Bottom and the second view's .Top , like this: 用当前代码解决此问题的最简单方法是跟踪第一个视图,并在它的.Bottom和第二个视图的.Top之间保持约束,如下所示:

if indexPath.row == 4 {

    var lastReviewView:ReviewView?;
    for index in 0..<2 {

        let reviewView = ReviewView()
        reviewView.translatesAutoresizingMaskIntoConstraints = false


        cell.addSubview(reviewView)
        cell.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[v0]-|",options: [],metrics: nil,views: ["v0" : reviewView]))

        if index == 0 {

            cell.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[v0(71)]",options: [],metrics: nil,views:["v0" : reviewView]))
            reviewView.backgroundColor = UIColor.redColor()
        }
        if index == 1 {
            cell.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(71)]-|",options: [],metrics: nil,views:["v0" : reviewView]))
            reviewView.backgroundColor = UIColor.blueColor()
        }

        if (lastReviewView != nil) {
            cell.contentView.addConstraint(NSLayoutConstraint(item: lastReviewView!, attribute: .Bottom, relatedBy: .Equal, toItem: reviewView, attribute: .Top, multiplier: 1.0, constant: 0.0))
        }

        lastReviewView = reviewView
        print(index)
    }

    return cell

}

If you are looking to deal with a variable amount of views stacked on each other, you could do it like this instead: 如果您要处理彼此堆叠的不同数量的视图,则可以这样做:

var reviewViews:[ReviewView] = [] // Fill this out with your loop
let contentView = cell.contentView
    var constraints:[NSLayoutConstraint] = []

let firstView = reviewViews.first
constraints.append(NSLayoutConstraint(item: contentView, attribute: .Top, relatedBy: .Equal, toItem: firstView, attribute: .Top, multiplier: 1.0, constant: 0.0))

for i in 0..<reviewViews.count {

    let view = reviewViews[i]
    constraints.append(NSLayoutConstraint(item: view, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 71.0))

    if i > 0 {
        let lastView = reviewViews[i-1]
        constraints.append(NSLayoutConstraint(item: lastView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 0.0))
    }

}

let lastView = reviewViews.last
constraints.append(NSLayoutConstraint(item: contentView, attribute: .Bottom, relatedBy: .Equal, toItem: lastView, attribute: .Bottom, multiplier: 1.0, constant: 0.0))

NSLayoutConstraint.activateConstraints(constraints)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM