我是 Swift 新手,正在尝试构建 YouTube 视频应用。 我在下面遇到了这个错误。
[14835:1757198] Could not cast value of type 'UITableViewCellContentView' (0x111d61280) to 'UIImageView' (0x111d4cdd0).
我的代码如下。
import UIKit
class tableview_blackpink: UIViewController , UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var videos:[Video] = [Video]()
override func viewDidLoad() {
super.viewDidLoad()
let model = VideoModel()
self.videos = model.getVideos()
self.tableView.dataSource = self
self.tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BasicCell")!
//let videoTitle = videos[indexPath.row].videoTitle
//Customize the cell to display the video
//cell.textLabel?.text = videoTitle
//Construct the video thumbnail url
let videoThumbnailUrlString = "http://i1.ytimg.com/vi/" + videos[indexPath.row].videoId + "/mqdefault.jpg"
//Create NSURL object
let videoThumbnailUrl = URL(string: videoThumbnailUrlString)
if videoThumbnailUrl != nil{
//Create NSURL request object
let request = URLRequest(url: videoThumbnailUrl!)
//Create NSURLSession
let session = URLSession.shared
//Create datatask and pass in the request
let dataTask = session.dataTask(with: request, completionHandler: {(data: Data?, response: URLResponse?, error: Error?) -> Void in
DispatchQueue.main.async{
//Get a reference to the imageView element of the cell
let imageView = cell.contentView.viewWithTag(1) as! UIImageView
//Create an image object from the data and assign it into the imageView
imageView.image = UIImage(data: data!)
}
})
dataTask.resume()
}
return cell
}
}
我在这里遇到了错误。
let imageView = cell.contentView.viewWithTag(1) as! UIImageView
我在谷歌上搜索了大量内容,得到的答案是解决这个问题
let imageView = cell.viewWithTag(1) as! UIImageView
到
let imageView = cell.contentView.viewWithTag(1) as! UIImageView
我尝试了这个,但仍然遇到同样的错误。 我正在关注this YouTube 视频教程和下面的代码不适用于最新版本。
Code for Swift2.2 is here 我很感激任何帮助。提前致谢。
最佳答案
如果在单元格 subview 中找不到(tag == 1),imageView 将为 nil。
let imageView = cell.subviews.first(where: { (temp) -> Bool in
return temp is UIImageView && temp.tag == 1
}) as? UIImageView
关于ios - 无法将类型 'UITableViewCellContentView' (0x111d61280) 的值转换为 'UIImageView' (0x111d4cdd0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50918291/