无法使用sender.title从我的按钮中获取标题(用于:...选择)
我正在学习iOS开发。 根据我的教程,我有下面的代码用于进行按钮反射演示。
import UIKit
class ViewController: UIViewController {
@IBAction func buttonPressed(_ sender: UIButton) {
let title = sender.title(for: .selected)!
let text = "\(title) buttion pressed"
out.text = text
}
@IBOutlet weak var out: UILabel!
}
单击模拟器中的按钮后,我有一个错误。
Unexpectedly found nil while unwrapping an Optional value
Let title = sender.title(用于:.Selected)!
导致此错误。 我的Xcode版本是13.4。
我通过拖动该按钮将其与该方法关联在一起。
我的按钮通过对情节板中的数据输入数据,通过double_click double_click进行标题名称“左”。
如果我删除!!
let title = sender.title(for:.selected)!
,我的标签可以显示nil按钮按下
。似乎iBoutlet可以正常工作。
我错过了获得按钮标题的任何意义吗?
I am learning ios development.
According to my tutorial, I have code as below for making a button reflection demo.
import UIKit
class ViewController: UIViewController {
@IBAction func buttonPressed(_ sender: UIButton) {
let title = sender.title(for: .selected)!
let text = "\(title) buttion pressed"
out.text = text
}
@IBOutlet weak var out: UILabel!
}
After I click the button in the simulator, I got an error.
Unexpectedly found nil while unwrapping an Optional value
let title = sender.title(for: .selected)!
causes this error.
My Xcode version is 13.4.
I have associated the button with the method correctly by dragging it.
My button has title names 'left' by double_clicking it and inputing the data left
in Storyboard.
If I delete the !
of let title = sender.title(for: .selected)!
, my label can show nil button pressed
.It is seems that IBOutlet can works fine.
Is there any point I missed for getting the title of my button?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是问题:您的教程太老了。它说的不是如今的工作方式。如果您不想学习现在的工作方式,请将按钮样式更改为默认故事板中的默认设置,以将按钮行为移动到过去,例如您的教程,然后您的代码将按照您的期望工作。
That's the problem: your tutorial is too old. What it says is not how things work nowadays. If you don't want to learn how things work now, then change the button style to Default in the storyboard to move the button behavior into the past, like your tutorial, and then your code will work as you expect.
您必须将iboutlet连接到情节板。我已经使用了您的代码,而且工作正常。请检查所附的屏幕截图。 image
You have to connect your IBOutlet to the storyboard. I have used your code and it's working fine. Please check the attached screenshot.Image
如果您在使用
.Selected
之前确定,这将有所帮助。您是否设置了按钮的选定状态标题。*更新的代码
It would help if you were sure before using
.selected
. Have you set the title for the selected state of the button.*Updated code