2016-07-04 169 views
1

我在包含UITextView的tableview中有一个单元格。 UITextview对uitableviewcell内容视图具有top,leading,trailing和bottom的限制。如果textview包含空文本,我想隐藏uitableviewcell。为此,我将单元格高度降低为0.由于textview具有相对于UITableViewCell设置的约束。隐藏包含UITextview的UITableviewcell(Autolayout)

UITableViewCell 
--------------------------- 
|   -T-   | 
| -L- UITextView -R- | 
|_________-B-_____________| 

L,T,B,R - 左,上,下,右约束

我得到的约束问题。

Unable to simultaneously satisfy constraints. 
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
     (1) look at each constraint and try to figure out which you don't expect; 
     (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x7fe5d58753a0 UITableViewCellContentView:0x7fe5d5874fe0.bottomMargin == UITextView:0x7fe5d399c000.bottom>", 
    "<NSLayoutConstraint:0x7fe5d58753f0 UITableViewCellContentView:0x7fe5d5874fe0.topMargin == UITextView:0x7fe5d399c000.top>", 
    "<NSLayoutConstraint:0x7fe5d5888a20 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7fe5d5874fe0(0.5)]>" 
) 

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7fe5d58753a0 UITableViewCellContentView:0x7fe5d5874fe0.bottomMargin == UITextView:0x7fe5d399c000.bottom> 

如何隐藏单元格而没有任何自动布局问题。

+0

你可以改变的顶部和底部的约束常数为0 –

+0

但电池是可重复的内容。我怎样才能改变约束?你能解释更多 –

+0

你如何设置高度为0,通过autolayout或通过heightForRow:atIndexPath? – 7vikram7

回答

1

我会变成约束关闭和使用active财产。这是最简单的方法,但要注意,它只能在iOS 8+工作,因为active财产上NSLayoutConstraint iOS中只加入8

首先确保你有一个IBOutletCollection数组包含所有你需要的约束:

@IBOutlet var allConstraints : [NSLayoutConstraint]! 

如果有的话,可以将它们连接到xib/storyboard中。否则,只需在代码中设置它们。

而且,在你要隐藏的单元格,执行情况:

cell.allConstraints.forEach { $0.active = false } 
在tableview中的数据源方法 -cellForRowAtIndexPath:

而且,重写-prepareForReuse:方法对细胞亚类如下:

override func prepareForReuse() { 
    super.prepareForReuse() 
    allConstraints.forEach { $0.active = true } 
} 

这折回的约束,这样的事情的行为正确如果隐藏单元被重复使用,以创建一个非隐藏细胞。

您可能还需要调用添加到setNeedsLayoutlayoutIfNeeded,但我想尝试没有他们下手 - 希望布局中通触发表视图的reloadData应该照顾你的东西 - 它总是不是最好的如果您不需要,请调用这些函数。

0

您可以将字符串的值保存在全局变量中,然后在cellForRowAtIndexPath中可以检查var是否为空,如果不是,则可以返回单元格。

像这样:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{ 
    if (your global var != nil) { 
     let cell: MyCell? = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as? MyCell 

     cell?.label.text = your value 

     return cell! 
    } 

} 
+0

感谢您的建议。但我更喜欢以自动布局的方式进行操作。你能帮我自动布局吗? –

0

试着改变约束的关系。取而代之的平等使用小于或等于

Contraints Settings