在我的代码中,我创建了一个循环,根据数组中有多少对象来创建UIView和UIButton。
一切正常工作,每次我按下删除按钮,就会从superview中删除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()
    }
}发布于 2015-10-26 15:38:31
没有设置标记的所有子视图都将有一个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 {这解决了这个问题,函数只会被调用一次。但你还会有其他问题:
发布于 2015-10-26 22:43:43
从iOS7开始,UIViewController提供和维护两个不可见视图,即顶部布局指南和底层布局指南,它们作为子视图注入其主视图的视图层次结构中。所以当你打电话
let CustomSubViews = self.view.subviews您也意外地获得了这些不可见的视图(您可以在调试器中自己看到),默认情况下,这就是为什么您的tag == 0语句中的代码在tag == 0时运行3次(一次用于您的视图,另2次用于那些不可见视图)。
tag == 0进行视图标识确实是个坏主意,因为在默认情况下所有视图都有此值.无论如何,当前代码最简单的修复方法是向上面提到的if语句添加条件:
// The invisible views are of type `_UILayoutGuide*`
if subview.tag == index && subview.isMemberOfClass(UIView.self)https://stackoverflow.com/questions/33349625
复制相似问题