Swift 3 - .addTarget()方法不触发Selector

时间:2017-05-03 02:49:03

标签: ios swift swift3

我正在尝试根据Firebase数据创建动态单选按钮。我希望将按钮排列在垂直堆栈中,基本上当它们被点击时,我希望它们消失并显示另一个视图:

class PollController: UIViewController {

@IBOutlet weak var passLabel: UILabel!
@IBOutlet weak var pollImage: UIImageView!
var ref: FIRDatabaseReference!
var pollRef: FIRDatabaseReference!

var pass = ""
var passedImageURL = ""

var posX = 0;
var posY = 0;

var buttons = [UIButton]()


override func viewDidLoad() {
    super.viewDidLoad()
    ref = FIRDatabase.database().reference()
    pollRef = ref.child("Polls").child(pass)
    passLabel.text = pass
    pollImage.sd_setImage(with: URL(string: passedImageURL), placeholderImage: UIImage(named: "test"))


    pollRef.observe(FIRDataEventType.value, with: {(snapshot) in
    let numberOfChildren = snapshot.childSnapshot(forPath: "answers").childrenCount
    self.passLabel.text = String(numberOfChildren)
    print(numberOfChildren)

    var stackView = UIStackView(arrangedSubviews: self.buttons)

        // create button1
    for x in 0..<numberOfChildren {
            let button = UIButton(frame: CGRect(x: self.posX, y: self.posY, width: 60, height: 20))
            button.setTitleColor(UIColor.black, for: .normal)
            button.setTitle("No", for: .normal)
            button.setImage(UIImage(named: "checkbox untick.png")!, for: .normal)
            // if the selected button cannot be reclick again, you can use .Disabled state
            button.setImage(UIImage(named: "checkboxredtick.png")!, for: .selected)
            button.tag = Int(x)
            button.addTarget(self, action: #selector(self.buttonAction(sender:)), for: .touchUpInside)

            stackView.addSubview(button)
            self.buttons.append(button)
            // create other buttons and add into buttons ...
        }
        })
    // Do any additional setup after loading the view.
}


func buttonAction(sender: UIButton!){
    for button in buttons {
        button.isSelected = false
    }
    sender.isSelected = true
    // you may need to know which button to trigger some action
    // let buttonIndex = buttons.indexOf(sender)
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
   }
}

enter image description here

2 个答案:

答案 0 :(得分:3)

如果您使用 SWIFT 3.0 或更高版本,

然后您必须定义如下所示的添加目标方法,因为选择器参数中缺少_:。

button.addTarget(self, action: #selector(buttonAction(_:)), for: .TouchUpInside)

同时检查您已在此处声明 myStackview 变量的ID。如果您声明然后尝试将其添加为:

 self.myStackview

答案 1 :(得分:1)

您的按钮声明为func buttonAction(sender: UIButton!)。请注意,sender之前没有下划线。这意味着您需要在调用函数时指定参数的名称。用参数名sender

替换选择器中的下划线
button.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)

您还可以在函数中的参数名称前添加下划线。

func buttonAction(_ sender: UIButton!)

另外,我注意到代码在Swift 3中看到了大部分语法。因此,Swift 3中内部修饰的控制事件是touchUpInside而不是TouchUpInside