我在表视图单元格中有一个集合视图。模型是按愿望列表名称分组的愿望列表项。可能有很多愿望清单。当用户选择愿望列表时,他们会得到一个愿望列表的平面数组,但我想在单元格中显示愿望列表项图像的预览。它们不能单独选择,单元格选择将转到所选愿望列表的项目列表。同样,我将删除整个愿望清单与刷卡删除动议。
我这里的问题是collectionView函数根本不启动。我正在测试的源数据有一个愿望列表和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
}
}
这是我的收藏视图单元格:
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
中实例化集合视图后,它看起来不像是将其添加到视图层次结构中。您需要在单元格的内容视图上调用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
}
如果表单元被重用,也可能会有一些问题。您必须确保每次使用集合视图委托时都对其进行了设置——可能是在
prepareForReuse
中。关于swift - UITableViewCell中的Swift UICollectionView无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41593845/