向按钮添加目标会打印出错误

时间:2019-02-23 00:30:51

标签: swift button selector

我有以下代码:

for i in 0...album.count-1 {
    let button: UIButton = {
        let bt = UIButton()
        bt.translatesAutoresizingMaskIntoConstraints = false
        bt.tintColor = UIColor.black
        bt.backgroundColor = .clear
        bt.addTarget(self, action: #selector(buttonPressed(sender: button, image: imageView)), for: .touchUpInside)
        bt.tag = i
        buttonPosition += 160
        bt.layer.cornerRadius = 5
        return bt
    }()

    //Stuff that you don't need

    let imageView: UIImageView = {
        let iv = UIImageView()
        iv.image = images[i]
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        iv.translatesAutoresizingMaskIntoConstraints = false
        return iv
    }()
}

@objc func buttonPressed(sender: UIButton!, image: UIImageView!) {
    let animator = UIViewPropertyAnimator.init(duration: 0.2, curve: .linear) {
        image.transform = CGAffineTransform.init(translationX: (image.frame.width + 12) * -1, y: image.frame.origin.y )
    }
    animator.startAnimation()
}

它会打印出此错误:

  

在其初始值内使用的变量

我该怎么做才能创建一个功能,将该按钮和我在循环中创建的imageView用作参数?

最后,如何创建本地功能?

1 个答案:

答案 0 :(得分:0)

您是从创建button的闭合中(在选择子句中)引用它的,这就是为什么出现此错误的原因。如果将#selector(buttonPressed(sender: button, image: imageView))更改为#selector(buttonPressed(sender: bt, image: imageView)),它应该可以正常工作。但是,更干净的方法是创建一个工厂函数,例如:

func makeButton(at position: CGFloat, taggedWith tag: Int) -> UIButton {
            let bt = UIButton()
            bt.translatesAutoresizingMaskIntoConstraints = false
            bt.tintColor = UIColor.black
            bt.backgroundColor = .clear
            bt.addTarget(self, action: #selector(buttonPressed(sender: button, image: imageView)), for: .touchUpInside)
            bt.tag = tag
            /// buttonPosition += 160 /// not sure what this is supposed to do but you'd use the position param here. 
            bt.layer.cornerRadius = 5
            return bt
}

然后您将调用此函数在循环中创建按钮。请注意,buttonPosition似乎未被使用。还要注意,您的按钮没有添加到集合或视图中,因此您可能需要检查按钮应该在哪里放置并相应地放置它们。