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

问题描述 投票:0回答:1

我有以下代码:

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()
}

它打印出这个错误:

变量在其自己的初始值内使用

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

最后,我该如何创建本地函数?

swift button selector
1个回答
0
投票

你从创建它的闭包中引用button(在selector子句中),这就是你得到这个错误的原因。如果你将#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似乎未被使用。另请注意,您的按钮未添加到集合或视图中,因此您可能需要检查按钮的居住位置并相应地放置它们。

© www.soinside.com 2019 - 2024. All rights reserved.