gpt4 book ai didi

UITableViewCell 中的 Swift UICollectionView 无法正常工作

转载 作者:行者123 更新时间:2023-11-28 15:56:56 25 4
gpt4 key购买 nike

我在 TableView 单元格中有一个 Collection View 。该模型是按愿望 list 名称分组的愿望 list 项目。可能有很多愿望 list 。当用户选择愿望 list 时,他们会得到一个平面数组的愿望 list ,但我想在单元格中显示愿望 list 的项目图像的预览。它们不可单独选择,单元格选择会转到所选愿望 list 的项目列表。同样,我将通过滑动删除 Action 删除整个愿望 list 。

我的问题是 collectionView 函数根本不触发。我正在测试的源数据有一个愿望 list 和 4 个项目。

这是我的 TableViewCell。

import Foundation
import UIKit
import Alamofire
import AlamofireImage

class WishListsCell: UITableViewCell {

var collectionView: UICollectionView!

let screenWidth = UIScreen.main.bounds.width

var alamofireRequest: Alamofire.Request?

override func awakeFromNib() {
super.awakeFromNib()
// Initialization code

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.itemSize = CGSize(width: screenWidth, height: ((screenWidth / 4) * Constants.IMAGE_ASPECT_RATIO))
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.estimatedItemSize.height = ((screenWidth / 4) * Constants.IMAGE_ASPECT_RATIO)
layout.estimatedItemSize.width = screenWidth

collectionView = UICollectionView(frame: contentView.frame, collectionViewLayout: layout)

collectionView.delegate = self

collectionView.dataSource = self

collectionView.register(WishListsCollectionViewCell.self, forCellWithReuseIdentifier: cellId)

self.contentView.addSubview(collectionView)

}

override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}


extension WishListsCell: UICollectionViewDelegate, UICollectionViewDataSource {


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

debugPrint(wishListItems.count)

return wishListItems.count

}


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WishListsCollectionViewCell", for: indexPath) as! WishListsCollectionViewCell

if let imageUrl = wishListItems[indexPath.row]["image"] as? String {

debugPrint(imageUrl)

cell.imageView.image = nil

if let image = ShoppingManager.sharedManager.photoCache.image(withIdentifier: imageUrl) {
cell.imageView.image = image
}
else
{
cell.alamofireRequest?.cancel()

cell.alamofireRequest = Alamofire.request(imageUrl)
.responseImage { response in

let img = response.result.value

cell.imageView.image = img

cell.imageView.contentMode = UIViewContentMode.scaleAspectFit

let imageWidth:CGFloat = self.screenWidth/4

let imageHeight:CGFloat = imageWidth * Constants.IMAGE_ASPECT_RATIO

cell.imageView.frame.size.width = imageWidth

cell.imageView.frame.size.height = imageHeight

ShoppingManager.sharedManager.photoCache.add(img!, withIdentifier: imageUrl)
}
}
}
return cell
}
}

这是我的 CollectionViewCell:

import Foundation
import UIKit
import Alamofire
import AlamofireImage

class WishListsCollectionViewCell: UICollectionViewCell {

var alamofireRequest: Alamofire.Request?

var imageView: UIImageView

let screenWidth = UIScreen.main.bounds.width

override init(frame: CGRect) {

imageView = UIImageView()

super.init(frame: frame)

contentView.addSubview(imageView)

imageView.translatesAutoresizingMaskIntoConstraints = false

imageView.contentMode = .scaleAspectFit

NSLayoutConstraint.activate([

NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal,
toItem: nil, attribute: .width,
multiplier: 1.0, constant: screenWidth / 4),

NSLayoutConstraint(item: imageView, attribute: .height, relatedBy: .equal,
toItem: nil, attribute: .height,
multiplier: 1.0, constant: (screenWidth / 4) * Constants.IMAGE_ASPECT_RATIO),

])
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

以下是我的 ViewController 代码的相关部分:

import UIKit
import Alamofire
import AlamofireImage
import MBProgressHUD
import DBAlertController

class WishListsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var tableView: UITableView = UITableView()

var screenSize: CGRect!
var screenWidth: CGFloat!
var screenHeight: CGFloat!

var cellId = "WishListsCell"

var didSelectItem:Bool = false

override func viewDidLoad() {
super.viewDidLoad()

screenSize = UIScreen.main.bounds
screenWidth = screenSize.width
screenHeight = screenSize.height

tableView.delegate = self

tableView.dataSource = self

tableView.backgroundColor = .white

tableView.register(WishListsCell.self, forCellReuseIdentifier: cellId)

self.view.addSubview(tableView)

tableView.translatesAutoresizingMaskIntoConstraints = false

tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

let customView = UIView(frame: CGRect(x:0, y:0, width:screenWidth, height:30))

customView.backgroundColor = Constants.APP_BACKGROUND_COLOR

let button = UIButton(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 30))

button.setTitle("Add New Wish List", for: .normal)

button.setTitleColor(Constants.APP_TEXT_COLOR, for: .normal)

button.titleLabel?.font = Constants.APP_HEADER_FONT

button.addTarget(self, action: #selector(addButtonAction), for: .touchUpInside)

customView.addSubview(button)

tableView.tableHeaderView = customView
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func numberOfSections(in tableView: UITableView) -> Int {
return wishLists.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

return 120
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! WishListsCell

let listId = wishLists[indexPath.section]["listid"] as! Int

cell.alamofireRequest?.cancel()

cell.alamofireRequest = Alamofire.request(myURL)
.responseJSON(completionHandler: {
response in
self.parseWishListItemData(JSONData: response.data!)
})
return cell
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

let listName = wishLists[section]["listname"] as! String

return listName
}
}

最佳答案

awakeFromNib 中实例化后,您似乎没有将 Collection View 添加到 View 层次结构中。您需要在单元格的内容 View 上调用 addSubview

override func awakeFromNib() {
super.awakeFromNib()
// Initialization code

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.itemSize = CGSize(width: screenWidth, height: ((screenWidth / 4) * Constants.IMAGE_ASPECT_RATIO))
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.estimatedItemSize.height = ((screenWidth / 4) * Constants.IMAGE_ASPECT_RATIO)
layout.estimatedItemSize.width = screenWidth

collectionView = UICollectionView(frame: contentView.frame, collectionViewLayout: layout)

collectionView.delegate = self

collectionView.dataSource = self

self.contentView.addSubview(collectionView) // <-- Need this
}

如果重复使用表格单元格,您可能还会遇到一些问题。您必须确保您的 Collection View 委托(delegate)在每次被重新使用时都得到设置——可能在 prepareForReuse 中。

关于UITableViewCell 中的 Swift UICollectionView 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41593845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com