【问题标题】:Add button only in Code?仅在代码中添加按钮?
【发布时间】:2014-10-08 17:53:26
【问题描述】:

我正在尝试仅在代码中添加按钮。在 Xcode 模拟器中它可以完美运行,但在我的设备上却不行:

fatal error: unexpectedly found nil while unwrapping an Optional value

我的代码:

@IBOutlet weak var playButton: UIButton!

override func viewDidLoad() {

    super.viewDidLoad()

    let image = UIImage(named: "playButton.png") as UIImage

    playButton   = UIButton.buttonWithType(UIButtonType.System) as UIButton
    playButton.frame = CGRectMake(10, 10, 100, 100) // crash is here
    playButton.center = CGPointMake(self.frame.width/2, self.frame.height/1.7)

    playButton.addTarget(self, action: "transition:", forControlEvents: UIControlEvents.TouchUpInside)
    playButton .setBackgroundImage(image, forState: UIControlState.Normal)

    self.view?.addSubview(playButton)

}

有人可以帮助我吗?

【问题讨论】:

  • 您的设备无法使用是什么意思?说它不起作用是没用的。
  • 我无法启动它,我有一个致命错误:“致命错误:在展开可选值时意外发现 nil”
  • 您提供的代码在哪里?这段代码在你的 viewController 的 viewDidLoad 方法中吗?
  • 是的。你可以看到我的编辑
  • IBOutlet 不应该写在它外面吗?还有self.frame确实是self.view.bounds,不是吗?

标签: ios iphone swift uibutton


【解决方案1】:

在 Xcode 模拟器中它可以完美运行,但在我的设备上却不行

这通常意味着您的代码与文件的实际名称不匹配。 MacOS X 文件系统通常 区分大小写,而 iOS 文件系统 区分大小写。因此,如果您的图像文件命名为 PlayButton.pngplayButton.PNG,但您指定了 playButton.png,则它通常可以在模拟器上运行,但不能在设备上运行。

确保代码中的文件名与项目中的文件匹配。

【讨论】:

  • 谢谢!我知道区分大小写,但这不是问题。我检查了,没问题
【解决方案2】:

这没有任何意义 - 如果您使用 @IBOutlet 这意味着您的按钮是在情节提要中创建的,因此您不需要初始化它:

let image = UIImage(named: "playButton.png") as UIImage

playButton   = UIButton.buttonWithType(UIButtonType.System) as UIButton
playButton.frame = CGRectMake(10, 10, 100, 100) // crash is here
playButton.center = CGPointMake(self.frame.width/2, self.frame.height/1.7)

playButton.addTarget(self, action: "transition:", forControlEvents: UIControlEvents.TouchUpInside)
playButton .setBackgroundImage(image, forState: UIControlState.Normal)

self.view?.addSubview(playButton)

删除所有上述代码并在情节提要中进行设置。 @IBAction 应该是一个单独的方法,它连接到故事板中按钮的 touchUpInside。

【讨论】:

  • 谢谢!我删除了@IBOutlet,因为我只希望我的按钮出现在代码中,而且它的工作原理就是这样。
  • 你知道如何在场景中添加按钮吗?当我在我的 GameScene 上添加我的代码(没有@IBOutlet)时,按钮不会出现。你知道为什么吗?
  • Haox,如果您指的是 SpriteKit 场景,我会检查 stackoverflow.com/questions/19082202/… 答案
【解决方案3】:

“Unwrapping an optionnal value”似乎是指您的 var 声明旁边的 !...如果您使用 ? 会怎样?

来自 Swift 文档

Trying to use ! to access a non-existent optional value triggers a runtime error. 
Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.

试试这个:

weak var playButton : UIButton?

并添加 ?在它之后访问它 - 就像你对 self.view?.addSubview 所做的那样,或者在你知道它已经被创建的方法中使用 ! 在本地强制展开它

(不过我不确定,还在学习语言... :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多