ios - Swift:将参数值传递给选择器函数

标签 ios 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)
}

谢谢。

最佳答案

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

func didTapAny(keyTitle: String){

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

func didTapAny(sender: UIButton) {

   // use here sender.currentTitle

}

关于ios - Swift:将参数值传递给选择器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24506979/

相关文章:

iphone - 架构 arm v7 的 undefined symbol

ios - Parse.com - 如何刷新用户信息

objective-c - 如何同时录制麦克风和钢琴

swift - 无法使用 SQLite.swift 打开数据库(新的/现有的)

ios - (Swift) 将数组存储和检索到 NSUserDefaults

ios - 将本地化文件添加到新的 IOS 7 应用程序

ios - UITableviewCell添加UITextfield导致detailTextLabel滑动 "up"

iphone - 配置时立即使用属性还是使用临时变量?

ios - iOS 14 SwiftUI 中不需要的位置动画

ios - 重新加载 pickerView 并同步