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

查看:122
本文介绍了Swift:将参数值传递给Selector函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将值从addKey函数传递给Selector函数(didTapAny函数),但无法确定如何。下面是我的代码:

I'm trying to pass value from addKey function to Selector function (didTapAny function) but couldn't figure how. 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)
}

谢谢。

推荐答案


//想要将上面函数的keyTitle传递给这个函数

// want to pass above function's keyTitle to this function

func didTapAny(keyTitle:String){

func didTapAny(keyTitle: String){

您无法将任何想要的内容传递给按钮操作方法。该方法将接收对该按钮的引用,您可以访问其 currentTitle 属性。它更像是:

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. It goes more like:

func didTapAny(sender: UIButton) {

   // use here sender.currentTitle

}

这篇关于Swift:将参数值传递给Selector函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆