2014-10-12 68 views
0

我已经创建了UITableView有很多静态UITableViewCell s。我已经将这些静态单元格中的一个样式更改为“自定义”。我为这个单元格创建了一个插座,以便我可以编程方式将子视图添加到它的contentView。在viewWillAppear中,我创建了一个UILabel并对其进行了适当的配置。然后我测试一些条件,如果它是真的,我创建一个UIView并添加UILabel作为子视图,然后我将UIView添加到单元的contentView。如果不是这样,我只需将UILabel本身添加到contentView如何重新创建一个UIView的UITableViewCell的contentView

这项功能在单元格第一次出现时效果很好,但是如果我执行push segue然后导航回去,contentView不会重置,因此它看起来与第一次出现时相同。它应该已经改变,因为检查的条件已经改变。我知道这是因为它只是添加了另一个子视图。所以我巧妙地在UIViewUILabel创建时巧妙地添加了一个tag,然后在运行代码以创建适当的视图之前,我从超级视图中删除了该视图,该视图为tag。我还存储了对UILabel(不是UIView)的引用,所以我将其设置为nil

最终结果是单元格在第一次呈现时显示得很好,但从push segue返回后,子视图按预期被删除,但未添加另一个子视图,因此单元格完全为空。我浏览了代码,它全部被调用,所以我不确定为什么在第一次删除它之后没有任何东西出现。

编辑:这必须是autoresizingMask的问题 - 设置框架手动工作。我怎样才能确保框架始终填充父框架?

//Store reference to UILabel and bool to test again 
var label: UILabel? 
var someCondition = false 

//viewWillAppear: 
cell.contentView.viewWithTag(100)?.removeFromSuperview() 
label = nil 

//This is the issue - frame is always size 1,1 
//label = UILabel(frame: CGRectMake(5, 5, 70, 20)) 
label = UILabel(frame: CGRectMake(0, 0, 1, 1)) 
label!.autoresizingMask = .FlexibleWidth | .FlexibleHeight 

label!.text = "testing" 
label!.backgroundColor = UIColor.whiteColor() 

someCondition = !someCondition 
if someCondition == true { 
    var view = UIView() 
    view.backgroundColor = UIColor.redColor() 
    //need to replace static frame with autoresizingMask here too 
    view.frame = CGRectMake(10, 10, 200, 70) 
    view.tag = 100 
    view.addSubview(label!) 
    cell.contentView.addSubview(view) 
} else{ 
    label!.tag = 100 
    cell.contentView.addSubview(label!) 
} 

回答

0

我无法复制出类似于您的代码的问题。我用下面的代码对它进行了测试。我在细节控制器中有一个unwind segue,它调用cameBackFromDetail,正如你所看到的,它只是否定了Bool的值。当我来回走动时,我发现细胞在具有标签的视图的单元格或标签之间交替。另一方面,如果我回去使用后退按钮,我会看到与我离开时相同的单元格,就像我应该那样。

class TableViewController: UITableViewController { 

    @IBOutlet weak var cell: UITableViewCell! 
    var label: UILabel? 
    var someCondition: Bool = false 

    override func viewWillAppear(animated: Bool) { 
     if let aView = cell.viewWithTag(100) { 
      aView.removeFromSuperview() 
      label = nil 
     } 
     label = UILabel(frame: CGRectMake(5, 5, 70, 20)) 
     label!.text = "testing" 
     label!.backgroundColor = UIColor.whiteColor() 
     if someCondition == true { 
      var view = UIView() 
      view.backgroundColor = UIColor.redColor() 
      view.frame = CGRectMake(10, 10, 200, 70) 
      view.tag = 100 
      view.addSubview(label!) 
      cell.contentView.addSubview(view) 
     }else{ 
      label!.tag = 100 
      cell.contentView.addSubview(label!) 
     } 
    } 


    @IBAction func cameBackFromDetail(segue: UIStoryboardSegue) { 
     someCondition = !someCondition 
    } 

} 
+0

谢谢你试试这个!我发现这个问题,这与添加/删除视图或标签无关。问题不在于将帧设置为固定大小,而是使用自动调整大小蒙版,并且不能正常工作 - 不知道为什么。我将用显示问题的代码编辑问题。 – Joey 2014-10-12 17:30:09

+0

@Joey,是的,我注意到了这一点,这就是为什么我的代码中没有这一行。 – rdelmar 2014-10-12 17:31:11

+0

当,我需要这个框架来调整,以始终填充父项。我认为这会起作用,很奇怪。我将如何实现这一目标? – Joey 2014-10-12 17:36:19