在我的代码中,我创建了一个循环,根据数组中的对象数创建UIView
和UIButton
s。
一切都按原样运行,每次按下删除按钮,都会从超级视图中删除UIView
。
但是,如果我第一次按下UIView
顶部的tag=0
删除按钮,则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()
}
}
答案 0 :(得分:1)
您未设置标记的所有子视图的标记均为0。
所以这里你的代码是找到标记值为0的其他子视图:
for subview in CustomSubViews {
if subview.tag == index {
只需使用以1开头的标签就可以了:
customButtonDeleteVideoUser.tag = index + 1
和
let index = sender.tag - 1
和
if subview.tag == index+1 {
这解决了问题,该函数只会被调用一次。但是你会遇到其他问题:
答案 1 :(得分:0)
从iOS7开始,UIViewController
提供并维护两个不可见的视图,顶部布局指南和底部布局指南,它作为子视图注入到查看其主视图的层次结构。所以当你打电话时
let CustomSubViews = self.view.subviews
您也不小心收到了这些不可见的观点(您可以在调试器中查看),默认情况下是tag == 0
,这就是if subview.tag == index
中代码的原因语句将在tag == 0
时运行3次(一次用于您的视图,另外两次用于那些不可见的视图)。
tag == 0
进行视图识别非常糟糕,因为默认情况下所有视图都有此值... 无论如何,对当前代码的最简单修复是为上述if
语句添加条件:
// The invisible views are of type `_UILayoutGuide*`
if subview.tag == index && subview.isMemberOfClass(UIView.self)