Can't Unwrap Optional.None When Setting Window Background Color

Can't unwrap Optional.None when setting window background color

Something in the self.view.window.backgroundColor chain (probably self.view.window) is nil. Many view- and view controller-related properties are implemented as implicitly unwrapped, which means that they are Optionals that you can treat like non-Optional variables for convenience's sake. Unfortunately, if you try to access one when it's nil you get the runtime error you're seeing.

Can you set the background color of the view's layer instead? view.window is nil when a view hasn't been added to a window, but view.layer should be there regardless.

Swift/IOS8 error: fatal error: Can't unwrap Optional.None

Is the Navigation Controller object self.navigationController nil?

The variable type on the navigationController property is an unwrapped optional. If your View Controller is not inside a UINavigationController that would be the problem.

To prevent the crash code along the following lines should be written:

if (self.navigationController)
{
self.navigationController.pushViewController(profileViewController, animated: true)
}

Alternatively you could write the code as:

self.navigationController?.pushViewController(profileViewController, animated: true)

The ? operator will prevent any further code from being executed, if self.navigationController evaluates to nil.

Why does UITextFIeld return optional value in Swift?

The reason is probably because you're using shouldChangeCharactersIn which doesn't indicate the change in the character until the second character. Ideally you want the user to be notified of the correct answer after they complete the answer and submit it, in which case you want to use something like textFieldDidEndEditing:

class MyVC: UIViewController, UITextFieldDelegate {
let textField = UITextField()
var numberLabel: UILabel {
let label = UILabel()
label.text = "100"
return label
}
let button = UIButton()

override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(textField)
textField.borderStyle = .roundedRect
textField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
textField.widthAnchor.constraint(equalToConstant: 200),
textField.heightAnchor.constraint(equalToConstant: 100)
])
textField.delegate = self

button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
button.tag = 1
button.backgroundColor = .black
button.setTitle("Answer", for: .normal)
self.view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.leadingAnchor.constraint(equalTo: textField.trailingAnchor),
button.widthAnchor.constraint(equalToConstant: 200),
button.heightAnchor.constraint(equalToConstant: 100)
])

}

@objc func buttonPressed(_ sender: UIButton!) {
if case let tag = sender.tag, tag == 1 {
textField.resignFirstResponder()
}
}

func textFieldDidEndEditing(_ textField: UITextField) {
//convert string into number
let input = (numberLabel.text! as NSString).integerValue

//find answer to label when added by 1111
let answer = input + 1111
print(answer)

if let numberText = Int(textField.text ?? "0") {
print("This is number text: \(numberText)")

if answer == numberText {
//if user gets answer correct
print("correct")
} else {
//if user gets answer incorrect
print("wrong")
}
}
}

}

Swift tableView.dequeueReusableCell Never Returning Nil

You don't need to check if the cell is nil using this dequeue method, as long as you've register a cell class for reuse, or provided a prototype in Interface Builder.

let cell = tableView.dequeueReusableCellWithIdentifier("CellSubtitle", forIndexPath: indexPath) as! UITableViewCell

If however, you want to continue manually initializing the cells, you can use the following dequeue method instead. (keep in mind, this is the old way)

let cell = tableView.dequeueReusableCellWithIdentifier("CellSubtitle") as? UITableViewCell

Then as far as initializing the detailTextLabel goes, you don't have to. It's built into the cell, and by specifying that the cell's style should be subtitle, that label will be set up for you.

Note that the casts aren't necessary in Swift 2.

Optional @ViewBuilder closure

Taking into account buildIf feature of ViewBuilder the following approach is possible that allows to keep ViewBuilder in init (that is preferable)

Tested & works with Xcode 11.2 / iOS 13.2

struct TopAndBottomView<Content>: View where Content: View {
let topContent: () -> Content
let bottomContent: () -> Content?

init(@ViewBuilder topContent: @escaping () -> Content,
@ViewBuilder bottomContent: @escaping () -> Content? = { nil }) {
self.topContent = topContent
self.bottomContent = bottomContent
}

var body: some View {
VStack {
topContent()
Spacer()
bottomContent()
}
}
}

So works as this one

struct TopAndBottomView_Previews: PreviewProvider {
static var previews: some View {
TopAndBottomView(topContent: {
Text("TOP")
}, bottomContent: {
Text("BOTTOM")
})
}
}

and this one

struct TopAndBottomView_Previews: PreviewProvider {
static var previews: some View {
TopAndBottomView(topContent: {
Text("TOP")
})
}
}


Related Topics



Leave a reply



Submit