Swift: 将参数值传递给选择器函数[英] Swift: Pass parameter value to Selector function

本文是小编为大家收集整理的关于Swift: 将参数值传递给选择器函数的处理方法,想解了Swift: 将参数值传递给选择器函数的问题怎么解决?Swift: 将参数值传递给选择器函数问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

我正在尝试将值从 addKey 函数传递给 Selector 函数(didTapAny 函数),但不知道如何.以下是我的代码:

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

谢谢.

推荐答案

//想把上面函数的keyTitle传给这个函数

func didTapAny(keyTitle: String){

你不能将任何你想要的东西传递给按钮操作方法.该方法将接收对按钮的引用,您可以访问它的 currentTitle 属性.它更像是:

func didTapAny(sender: UIButton) {

   // use here sender.currentTitle

}

本文地址:https://www.itbaoku.cn/post/924396.html