问题
I am simply trying to connect a variable with a UILabel in Swift. I have looked at many tutorials but I keep getting errors. The main cause seems to be that @IBOutlet weak var str = UILabel!
is always nil. When I try to assign a value to it, the console prints a fatal error: unexpectedly found nil while unwrapping an Optional value
and inside the coding interface, the line self.stringLabel.text = self.string
is highlighted with the error Thread 1: EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0
. Here is my code:
@IBOutlet weak var stringLabel: UILabel!
var string: String!
override func viewDidLoad() {
self.stringLabel.text = self.string
super.viewDidLoad()
}
@IBAction func buttonClick(sender: UIButton) {
self.stringLabel.text = "Button clicked!"
}
I have tried different positioning of the .self
and .text
around the variables and have had no success. Am I on the right track? And, if so, what amI doing wrong? If I'm completely wrong, how does one set a label's text to that of a variable? Thank you very much in advance.
EDIT: I have connected the label in the storyboard to the @IBOutlet
e
回答1:
Cocoa will take care of your UILabel if you have it connected within interface builder (make sure that's the case) but your string object is uninitialized, you have to allocate it with var string: String = ""
or if you want to use an optional var string: String? = ""
You can do this in the global scope but I would recommend that all of your view controllers have an init()
method where these sorts of things are assigned.
Edit: I tried reproducing the problem, but I got an expected result. Here is my code for the view controller
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var testLabel: UILabel!
var string: String!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
string = "Hello World"
}
override func viewDidLoad() {
self.testLabel.text = self.string
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
回答2:
The issue is that the variable string
is nil
.
An implicit unwrapped optional (!
) must be non-nil when being used.
Try something real:
var string = "Hello there"
回答3:
The stringLabel property is NOT connected to Interface Builder
You must connect the UILabel
object in Interface Builder to the property in your Swift code.
- In Xcode open side by side the xib/storyboard representing your UI and the Swift View Controller
- Keep ctrl pressed on the keyboard
- Move the pointer over the UILabel object in Interface Builder
- Press the pointer button
- Drag the pointer from the
UILabel
(Interface Builder) to theUILabel!
part in your declaration@IBOutlet weak var stringLabel: UILabel!
in your Swift source code
That's it.
来源:https://stackoverflow.com/questions/35417025/why-is-my-uilabel-variable-always-nil