我有一个 UITableView,由具有 2 个段的 UISegmentControl 控制。
在第 1 段中,我以编程方式向单元格 subview 添加一些 View ,以向单元格添加一些视觉元素。
当用户切换到分段 2 时,我希望这些以编程方式添加的 View 消失。但他们坚持!当我切换到 Segment 2 时,我不知道如何让它们消失。
一些代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ProfilePokemonTableViewCell
var views: [String: UIView] = [:]
var piechart = Piechart2()
switch(segmentedControl.selectedSegmentIndex)
{
case 0:
let i:Int = indexPath.row
let curItem = self.pokemonAndIds[i]["data"] as! NSDictionary
let name = self.pokemonAndIds[indexPath.row]["data"]!!["name"] as! String
// MARK: - Add Piechart view programmaticaly
var views: [String: UIView] = [:]
var error = Piechart2.Slice()
error.value = 100 - CGFloat(aveIV)
error.color = UIColor.magentaColor()
error.text = "Error"
var win = Piechart2.Slice()
win.value = CGFloat(aveIV)
win.color = UIColor(netHex:0x6cedb8)
win.text = "Winner"
piechart.title = "42"
piechart.activeSlice = 1
piechart.radius.inner = 12
piechart.radius.outer = 23
piechart.layer.borderWidth = 0
piechart.slices = [error, win]
piechart.subtitle = ""
piechart.translatesAutoresizingMaskIntoConstraints = false
cell.addSubview(piechart)
views["piechart"] = piechart
cell.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[piechart(==66)]-10-|", options: [], metrics: nil, views: views))
cell.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-5-[piechart(==66)]", options: [], metrics: nil, views: views))
break
case 1:
cell.nameLabel.text = self.userFriendList["data"]![indexPath.row]["name"] as! String
break
default:
break
}
在上面的代码中,当我切换到第二段时,会出现饼图元素。我不知道如何隐藏它、将其从 View 中删除、删除它或使其不出现在第二段中所需的任何操作。
最佳答案
当您在 cellForRowAtIndexPath
方法中重新实例化 PiChart 对象时,您不再拥有对屏幕上可以看到的 PiChart 的引用。也就是说,此时应该重新创建单元格,但我知道这不会发生。尽管这无论如何都不是一个理想的解决方案,但仅仅为了证实怀疑就值得尝试。
尽管我讨厌像这样爬入 View 层次结构,但如果您丢失了对对象的引用,有时它可能是更好的方法。
for subview in cell.contentView.subviews {
if let pichart = subview as? Piechart2 {
pichart.removeFromSuperview()
}
}
关于iOS:当分段控件更改时隐藏或删除以编程方式添加的 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39701258/