删除特定的子视图(swift)

时间:2016-06-29 01:42:34

标签: swift

问题:如何删除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
}

2 个答案:

答案 0 :(得分:3)

尝试这样:

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

NicolasMiari的建议方式:

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

答案 1 :(得分:1)

如果您只想删除deptmentProfile

中的所有子视图
for subview in deptmentProfile.subviews {
    subview.removeFromSuperview()
}

如果你的意思是删除UIButton类型的子视图,使用where子句是一种正确而优雅的方式

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