import UIKit class ViewController: UIViewController { private let imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.backgroundColor = .white return imageView }() private let button: UIButton = { let button = UIButton() button.backgroundColor = .white button.setTitle("Button", for: .normal) button.setTitleColor(.orange, for: .normal) return button }() let colors: [UIColor] = [ .systemRed,.systemBlue,.systemGreen,.systemOrange,.systemGray6] override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemGray // Do any additional setup after loading the view. view.addSubview(imageView) imageView.frame = CGRect(x: 50, y: 150, width: 300, height: 300) imageView.center = view.center view.addSubview(button) getRandomPhoto() button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside) } @objc func didTapButton() { getRandomPhoto() view.backgroundColor = colors.randomElement() } override func viewWillLayoutSubviews() { super.viewDidLayoutSubviews() button.frame = CGRect(x: 30, y: view.frame.size.height-150-view.safeAreaInsets.bottom, width: view.frame.size.width-60, height: 55) } func getRandomPhoto() { let urlString = "https://source.unsplash.com/random/600×600" let url = URL(string: urlString)! guard let data = try? Data(contentsOf: url) else { return } imageView.image = UIImage(data: data) } }
Xcode初心者です。
コードを打ち終わりシュミレーションをしようとすると強制終了になり、let url = URL(string: urlString)!というコードの横にThread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional valueというエラーが表示されます。
解決方法を教えてください。
回答1件
あなたの回答
tips
プレビュー