我有一个包含UITableView
的UIViewController
,根据我的逻辑为UITableViewCell
创建了单独的类,我想为每一行传递数组。因此,我创建了一个可变数组,并在方法的单元格调用时分配新值。
但是我无法从UITableViewCell
类访问可变数组
我使用了以下代码
class PostPage: UIViewController{
public var imageArray = [String] ()
}
extension PostPage: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if self.UserDatas?.posts.app[indexPath.row].images?.count ?? 0 > 0 {
let cell:PostImageCell = tablView.dequeueReusableCell(withIdentifier: "PostImageCell") as! PostImageCell
self.imageArray = self.UserDatas?.posts.app[indexPath.row].images ?? ["String URL"]
cell.selectionStyle = .none
return cell
}
}
class PostImageCell: UITableViewCell{
override func awakeFromNib() {
super.awakeFromNib()
var mainClass : ViewController = ViewController()
let image = self.mainClass.imageArray
}
}
}
下面是我得到的错误,类似于"类型为'ViewController'的值没有成员'imageArray'">。
首先您没有名为ViewController
的VC
var mainClass : ViewController = ViewController()
let image = self.mainClass.imageArray
第二次您可以使阵列成为全局
class Service {
static let shared = Service()
var imageArray = [String] ()
}
然后在所有的应用程序中像这样使用它
Service.shared.imagArray
或者在单元格自定义类中创建另一个
class PostImageCell: UITableViewCell{
var imageArray = [String] ()
}
并在cellForRowAt
中分配
let cell = //
cell.imageArray = imageArray
您的代码无法工作。
反其道而行,并通过cellForRow
中的阵列
class PostImageCell: UITableViewCell {
var imageArray = [String]()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostImageCell") as! PostImageCell
cell.imageArray = self.UserDatas?.posts.app[indexPath.row].images ?? []
cell.selectionStyle = .none
return cell
}
没错"类型为‘ViewController’的值没有成员‘imageArray’">
PostPage成功了!!!
更改此项:var mainClass: ViewController = ViewController()
对此:var mainClass: PostPage = PostPage()
那个错误会消失的。
但请记住:它是一个新的初始化对象,本身不包含任何内容。