在我的代码中,我创建了一个循环,根据数组中的对象数量创建 UIView
和 UIButton
。
一切都按预期进行,每次我按下删除按钮时,UIView
就会从 super View 中删除。
但是,如果我第一次按下带有 tag=0
的顶部 UIView
中的删除按钮,则会重复执行 loadUser
3多次导致应用程序崩溃。
我的代码哪里做错了?
var customViewUser: UIView?
var names:NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
userNames()
LoadUsers()
}
func userNames(){
names = ["aaa", "bbb", "ccc", "ddd", "eee", "fff"]
}
func LoadUsers() {
let countUsers = names.count
print("\(countUsers) Users")
for (index, _) in names.enumerate() {
print("User n: \(index)")
let userNameViewsY = CGFloat(index * 128)
//FIRST USER VIEW
customViewUser = UIView(frame: CGRectMake(0, userNameViewsY, self.view.frame.size.width, 128))
customViewUser!.backgroundColor=UIColor.greenColor()
customViewUser!.layer.borderColor = UIColor.lightGrayColor().CGColor
customViewUser!.layer.borderWidth = 3
customViewUser!.tag = index
self.view.addSubview(customViewUser!)
let customButtonDeleteVideoUser = UIButton(frame: CGRectMake(customViewUser!.frame.size.width - 200, 4, 100, 28))
customButtonDeleteVideoUser.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
customButtonDeleteVideoUser.setTitle("Delete", forState: UIControlState.Normal)
customButtonDeleteVideoUser.addTarget(self, action: "deleteButton:", forControlEvents:.TouchUpInside)
customViewUser!.addSubview(customButtonDeleteVideoUser)
// set tag
customButtonDeleteVideoUser.tag = index
}
}
func deleteButton(sender: UIButton) {
let index = sender.tag
print(" User \(index) selected")
let CustomSubViews = self.view.subviews
for subview in CustomSubViews {
if subview.tag == index {
print(subview.tag)
if index >= 0 {
subview.removeFromSuperview()
names.removeObjectAtIndex(index)
print(names)
LoadUsers()
}
}
subview.removeFromSuperview()
}
}
最佳答案
所有未设置标签的 subview 的标签均为 0。
因此,您的代码正在查找标记值为 0 的其他 subview :
for subview in CustomSubViews {
if subview.tag == index {
只要使用以 1 开头的标签就可以了:
customButtonDeleteVideoUser.tag = index + 1
和
let index = sender.tag - 1
和
if subview.tag == index+1 {
这解决了问题,并且该函数只会被调用一次。但你还会遇到其他问题:
- 当删除各种 View 时,数组会变短,并且您将拥有没有相应数组位置的标签:如果不更新标签,names.removeObjectAtIndex(index) 将崩溃
- 而且,当您删除一个 View 时,您似乎会添加更多 View ,不确定这是否是故意的。
关于ios - Swift 2.0 - NSMutableArray - 删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33349625/