从视图中删除按钮
有没有办法清除所有按钮的视图?我的代码每秒都会生成按钮,并且我制作了一个按钮,我想将它们全部从屏幕上清除。当我尝试 [brick.removeFromSuperview]
(brick 是按钮的名称)时,它只删除了生成的最后一个按钮。
Is there a way to clear the view of all buttons? My code generates buttons every second, and I made a button that I want to clear them all off the screen. When I tried [brick.removeFromSuperview]
(brick being the name of the button), it only deleted the last button that was produced.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在
NSMutableArray
中跟踪对所有按钮的引用。ex
此方法的一个优点(与仅枚举视图的子视图并查找按钮相反)是,您不必担心从视图中删除不应删除的 UIButton。例如,如果您不希望删除“删除所有按钮”按钮,则不要将其添加到数组中。
You could keep track of the references to all your buttons in an
NSMutableArray
.e.x.
An advantage of this method (as opposed to just enumerating the view's subviews and looking for buttons) is that you don't have to worry about removing UIButtons from your view that shouldn't be. For example, if you don't want your "delete all buttons" button removed, just don't add it to the array.
但要小心,这实际上会删除指定视图中的所有按钮。因此,您可能需要某种条件来仅删除生成的按钮。您可以通过在其他按钮上设置
标签
来区分生成的按钮,如果该按钮没有标签,则将其删除。Careful though, this will literally delete all buttons from the specified view. So you probably want some kind of conditional to only delete the generated buttons. You could distinguish from generated buttons by setting a
tag
on your other buttons, if the button has no tag then remove it.需要临时数组,因为删除按钮会使枚举器失效,从而产生不可预测的结果。
The temporary array is required because removing the button invalidates the enumerator producing unpredictable results.