ios 从ScrollView Swift中删除子视图

ql3eal8s  于 2023-10-21  发布在  iOS
关注(0)|答案(4)|浏览(120)

我使用for循环在scrollView中创建标签和按钮。是否可以删除scrollView中的所有对象?(我想更新新的内容)

for peop in personArray{

        scrollView.clearContent ??????

        // Name label
        var label: UILabel = UILabel()
        label.frame = CGRectMake(8, CGFloat(nameHeight), 183, 21)
        label.backgroundColor = UIColor.whiteColor()
        label.textColor =  UIColor(red: 90/255.0, green: 187/255.0, blue: 206/255.0, alpha: 1.0)
        label.textAlignment = NSTextAlignment.Left
        label.font = UIFont (name: "HelveticaNeue-Light", size: 14)
        label.text = " \(peop.getName()) - \(sex)"
        self.scrollView.addSubview(label)

        //Delete button
        var button = UIButton.buttonWithType(UIButtonType.System) as UIButton
        button.tag = playerId
        button.frame = CGRectMake(199, CGFloat(nameHeight), 37, 21)
        button.backgroundColor = colorWheel.colorsArray[7]
        button.setTitle("Slet", forState: UIControlState.Normal)
        button.addTarget(self, action: "delAction:", forControlEvents: UIControlEvents.TouchUpInside)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        self.scrollView.addSubview(button)
        button.titleLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 14)

        scrollHeight = scrollHeight + 29
        nameHeight = nameHeight + 29
        playerId++
    }
    scrollView.contentSize = CGSize(width: 20.0, height: CGFloat(nameHeight))
}

func delAction(sender: UIButton!){
    personArray.removeAtIndex(sender.tag)
    updatePeople()
}
dgsult0t

dgsult0t1#

你试过这个吗?

let subViews = self.scrollView.subviews
for subview in subViews{
    subview.removeFromSuperview()
}
91zkwejq

91zkwejq2#

单线解决方案,使用

scrollView.subviews.forEach({ $0.removeFromSuperview() })

更新

如果只删除特定类型的视图,比如UIButton,请使用

scrollView.subviews.forEach ({ ($0 as? UIButton)?.removeFromSuperview() })
tcomlyy6

tcomlyy63#

你可以用积木式教学法,

let views: NSArray = scroller.subviews

// 3 - remove all subviews
views.enumerateObjectsUsingBlock {
(object: AnyObject!, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
  object.removeFromSuperview()
}
lh80um4z

lh80um4z4#

  • Swift 5.9*

我们可以使用下面的代码,如果我们想删除特定的对象,否则我们可以直接使用currentView.removeFromSuperview()

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

相关问题