前提・実現したいこと
storyboardを使用せずにコードで入力してますが、カスタムセルの設定のみ「xib」を作成してやっています。
エラーが出てるので解消してtableに表示させたいです。
発生している問題・エラーメッセージ
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
該当のソースコード
swift4 import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { /// 画像のファイル名 let imageNames = ["1.png", "2.png", "3.png"] /// 画像のタイトル let imageTitles = ["001", "002", "003"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let myTableView = UITableView(frame: view.frame, style: .plain) myTableView.rowHeight = 70 myTableView.delegate = self myTableView.dataSource = self myTableView.register(CustomCellTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(CustomCellTableViewCell.self)) self.view.addSubview(myTableView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// セルの個数を指定するデリゲートメソッド(必須) func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return imageNames.count } /// セルに値を設定するデータソースメソッド(必須) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // セルを取得 let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(CustomCellTableViewCell.self), for: indexPath) as! CustomCellTableViewCell // セルに値を設定 cell.setCell(imageName: imageNames[indexPath.row], titleText: imageTitles[indexPath.row]) return cell } }
swift4 import UIKit class CustomCellTableViewCell: UITableViewCell { var myImage: UIImage! @IBOutlet weak var myImageView: UIImageView! @IBOutlet weak var myLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } /// 画像・タイトルを設定するメソッド func setCell(imageName: String, titleText: String) { myImageView.image = UIImage(named: imageName) //ここでエラー myLabel.text = titleText //ここでもエラー } }
試したこと
myImageView.image = UIImage(named: imageName) //ここでエラー myLabel.text = titleText //ここでもエラー
の部分を
myImage = UIImage(named: imageName) myImageView = UIImageView(image: myImage) myLabel?.text = titleText //ここでもエラー
にしたところエラーは消えましたが画像やラベルの表示がされませんでした。
補足情報(FW/ツールのバージョンなど)
Xcode : Version 9.4.1
Swift4.1.2
回答1件
あなたの回答
tips
プレビュー