我试图让CustomCell槽观看YouTube教程,但我在Tableview中遇到了这个问题。 类型'CustomCell'的值没有成员'mainImage'。我希望你们中的一些人可以帮助我解决这个问题。
我想在单元格中获取的mainImage在CustomCell.swift中。
我的TableViewController:
import UIKit
struct CellData {
let image : UIImage?
let message : String?
}
var data = [CellData]()
class TableViewController : UITableViewController{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
data = [CellData.init(image: #imageLiteral(resourceName: "Bildschirmfoto 2018-09-20 um 22.17.11"), message: "The Avengers")]
self.tableView.register(CustomCell.self, forCellReuseIdentifier: "custom")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "custom") as! CustomCell
cell.mainImage = data[indexPath.row].image
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
<#code#>
}
}
我的CustomCell
import Foundation
import UIKit
var message : String?
var mainImage : UIImage?
var messageView: UITextView = {
var textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
return textView
}()
var mainImageView: UIImageView = {
var imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
class CustomCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier:reuseIdentifier)
self.addSubview(mainImageView)
self.addSubview(messageView)
mainImageView.leftAnchor.constraint(equalTo:self.leftAnchor).isActive = true
mainImageView.topAnchor.constraint(equalTo:self.topAnchor).isActive = true
mainImageView.bottomAnchor.constraint(equalTo:self.bottomAnchor).isActive = true
mainImageView.widthAnchor.constraint(equalTo:self.heightAnchor).isActive = true
messageView.leftAnchor.constraint(equalTo:mainImageView.rightAnchor).isActive = true
messageView.rightAnchor.constraint(equalTo:self.rightAnchor).isActive = true
messageView.bottomAnchor.constraint(equalTo:self.bottomAnchor).isActive = true
messageView.topAnchor.constraint(equalTo:self.topAnchor).isActive = true
}
override func layoutSubviews() {
super.layoutSubviews()
if let message = message {
messageView.text = message
}
if let image = mainImage {
mainImageView.image = image
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
答案 0 :(得分:1)
您必须将子视图放入单元格类:
class CustomCell: UITableViewCell {
var messageView: UITextView = {
var textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
return textView
}()
var mainImageView: UIImageView = {
var imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
...
}