ios 如何从按钮获取标签名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26074239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:51:28  来源:igfitidea点击:

How to get label name from Button?

iosswift

提问by Dharmesh Kheni

I am new in Swiftand I am making a simple calculator where I wan't to detect a button which was pressed and my code is below.

我是新手,Swift我正在制作一个简单的计算器,我不想检测按下的按钮,我的代码如下。

 @IBAction func ButtonTapped(TheButton : UIButton){

    println(TheButton.titleLabel.text)
}

But It Shows me error like "UILabel? Does not have a member a named text"

但它向我显示了错误 "UILabel? Does not have a member a named text"

and it tell me to modify code like this

它告诉我像这样修改代码

println(TheButton.titleLabel?.text)

This Prints Optional("1")(1 is my button name)

此打印件Optional("1")(1 是我的按钮名称)

So anybody can help me why this is happend to me and how can I print my button name without Optional?

所以任何人都可以帮助我为什么这会发生在我身上,以及如何在没有 Optional 的情况下打印我的按钮名称?

回答by Kirsteins

If you are sure that titleLabelis not nil:

如果您确定titleLabel不是nil

println(TheButton.titleLabel!.text)

else

别的

if let text = TheButton.titleLabel?.text {
    println(text)
}

回答by Andrew K

More simply, you could just do:

更简单地说,你可以这样做:

let titleValueString = TheButton.currentTitle!

If the button's title is not nil, the exclamation point (!) will implicitly unwrap the optional (currentTitle without the exclamation point) and you will have a string value for the title of the button in your constant, titleValueString

如果按钮的标题不是 nil,感叹号 ( !) 将隐式展开可选的(不带感叹号的 currentTitle),并且您将在常量中获得按钮标题的字符串值,titleValueString

回答by Horatio

The top answer no longer works. Here is the corrected version for Swift 2.2:

最佳答案不再有效。这是 Swift 2.2 的修正版本:

If you are sure that titleLabel is not nil:

如果您确定 titleLabel 不为零:

print(TheButton.titleLabel!.text!)

If you are not:

如果你不是:

if let text = TheButton.titleLabel?.text {
    print(text)
}