删除特定的子视图(Swift)

4
问题:如何仅删除UIButton的所有子视图? 如果我删除所有子视图,它也会删除单元格标题。
这是我的代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("idcell", forIndexPath: indexPath) as UITableViewCell
    let lblTitle : UILabel = cell.contentView.viewWithTag(101) as! UILabel
    lblTitle.text = (deptId[indexPath.row] as? String)! + "     " + (deptDesc[indexPath.row] as? String)!
    var height:CGFloat = 0
    cell.backgroundColor = UIColor.whiteColor()
    cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator

    if(indexPath == selectedIndexPath){
        cell.backgroundColor = UIColor.grayColor()
        for i in 0...deptProfile.count-1 {
            let deptmentProfile = UIButton(frame: CGRectMake(0,44+height,400,41))
            deptmentProfile.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
            height = height+41
            deptmentProfile.setTitle(deptProfile[i] as! String, forState: UIControlState.Normal)
            deptmentProfile.setTitleColor(UIColor.blackColor(), forState: .Normal)
            deptmentProfile.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
            deptmentProfile.backgroundColor = UIColor.whiteColor()
            deptmentProfile.titleEdgeInsets = UIEdgeInsetsMake(0, 40, 0, 0); //margin to the left
            cell.addSubview(deptmentProfile)
        }
        cell.accessoryType = UITableViewCellAccessoryType.None
    } 
    return cell
}

“删除UIButton的所有子视图?”您在代码中添加了一个UIButton,您在哪里将其删除?请在您的问题中更加详细地说明您正在做什么以及您试图做什么,但是却无法正常工作。 - Santosh
2个回答

11

试试这样:

for view in subviews {
    if view is UIButton {
       view.removeFromSuperview()
   }
}

NicolasMiari提出的建议方式:

for view in subviews  where view is UIButton{
    view.removeFromSuperview()
}

这也可以。但是 where 风格更符合 Swift 的风格,而且嵌套更少。 - Nicolas Miari

1
如果你只想从deptmentProfile中删除所有子视图
for subview in deptmentProfile.subviews {
    subview.removeFromSuperview()
}

如果你想要移除类型为 UIButton 的子视图,使用 where 子句是一个适当而优雅的方式。
for subview in testButton.subviews where subview is UIButton {
    subview.removeFromSuperview()
}

不,我不想删除所有的子视图。我只想删除UIButton的子视图。 - carmelo
deptmentProfile 是 UIButton,所以我的答案是移除 UIButton 的子视图。有问题吗? - ronan
也许他的意思是“类型为UIButton的子视图”?如果是这样,添加where subview is UIButton就可以解决问题了。 - Nicolas Miari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接