###前提・実現したいこと
URLから画像ファイルを取ってきて、ボタンに設置しようとするところで、行き詰まっています。
###該当のソースコード
Swift
1 2 let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! CustomTableViewCell 3 4 let userProfileImage: UIImage = self.downloadProfileImage(from: hisData["userImage"]! as! String)! 5 cell.userImage.setImage(userProfileImage, for: UIControlState()) 6 7 8 9 // プロフィール画像(Button)を取得 10 func downloadProfileImage(from imgURL: String!) -> UIImage? { 11 let url = URLRequest(url: URL(string: imgURL)!) 12 var imageData = UIImage() 13 let task = URLSession.shared.dataTask(with: url) { 14 (data, response, error) in 15 if let error = error { 16 print(error.localizedDescription) 17 return 18 } 19 20 if let data = data { 21 DispatchQueue.main.async { 22 imageData = UIImage(data: data as Data)! 23 } 24 } 25 26 27 } 28 task.resume() 29 return imageData 30 31 } 32 33 34CustomTableViewCell.swift //identifier → postCell 35 36class CustomTableViewCell: UITableViewCell { 37 38 var delegate: UIViewController? 39 40 @IBOutlet weak var userImage: UIButton! 41 42} 43 44
###補足情報
hisData["userImage"]には画像のURLが入っていることをプリントして確認しました。
エラーなどは特に出ず、画像を入れようとしているボタンもきちんと動いています。
ただ、画像だけが表示されません...
よろしくお願いいたします。
不明点などは、ご指摘いただければ改善いたします。
処理は if let data = data {} の中に入っていますか?入っているなら print(UIImage(data: data as Data)!) の出力を教えて下さい。
UIButtonにsetImageする処理はfunc tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {}の中に入っています。なのでif let data = data {}を記述すると、Use of unresolved identifier 'data'と出ます。downloadProfileImage(){}内のimageData = UIImage(data: data as Data)!の直後にprintすると<UIImage: 0x1c42aac20>, {746, 750}と出力されました。
(deleted)
セルに乗せているボタンに画像をセットしているのであれば、その部分のコードを書いて下さい。
カスタムセルを作成していて、最上部で指定しているcellの中のuserImageというoutletに値を入れようと試みました。
回答1件
あなたの回答
tips
プレビュー