简体   繁体   English

Swift:将参数值传递给Selector函数

[英]Swift: Pass parameter value to Selector function

I'm trying to pass value from addKey function to Selector function (didTapAny function) but couldn't figure how. 我正在尝试将值从addKey函数传递给Selector函数(didTapAny函数),但无法计算。 Below is my code: 下面是我的代码:

var keyName: UIButton!
func addKey(var keyTitle: String, var yValue: Float32){
    keyName = UIButton.buttonWithType(.System) as UIButton
    keyName.setTitle(keyTitle, forState: .Normal)
    keyName.sizeToFit()
    keyName.setTranslatesAutoresizingMaskIntoConstraints(false)

    // Couldn't figure how to pass parameter value to Selector at this line
    // action: Selector("didTapAny:")
    keyName.addTarget(self, action: "didTapAny", forControlEvents: .TouchUpInside)

    keyName.titleLabel.font = UIFont.systemFontOfSize(24)
    keyName.backgroundColor = UIColor(white: 0.9, alpha: 9)
    keyName.layer.cornerRadius = 5
    view.addSubview(keyName)
    var keyNameButtonLeftSideConstraint = NSLayoutConstraint(item: keyName, attribute: .CenterY, relatedBy: .Equal, toItem:view, attribute:.CenterY, multiplier: 1.0, constant: 0.0)
    var keyNameButtonBottomConstraint = NSLayoutConstraint(item: keyName, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1.0, constant: yValue)
    view.addConstraints([keyNameButtonLeftSideConstraint, keyNameButtonBottomConstraint])
}

// want to pass above function's keyTitle to this function
func didTapAny(keyTitle: String){
    var proxy = textDocumentProxy as UITextDocumentProxy
    proxy.insertText(keyTitle)
}

Thanks. 谢谢。

// want to pass above function's keyTitle to this function //要传递函数的keyTitle到此函数

func didTapAny(keyTitle: String){ func didTapAny(keyTitle:String){

You cannot pass whatever you wish into a button action method. 您无法将所需的任何内容传递给按钮操作方法。 The method will receive a reference to the button and you can access its currentTitle property. 该方法将收到对该按钮的引用,您可以访问其currentTitle属性。 It goes more like: 它更像是:

func didTapAny(sender: UIButton) {

   // use here sender.currentTitle

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM