0

我有一个表视图单元格内的集合视图。该模型是按愿望清单名称分组的愿望清单项目。可能有许多愿望清单。当用户选择愿望清单时,他们会得到一系列希望清单,但我希望在单元中显示愿望清单的项目图像预览。它们不是单独选择的,单元格选择将转到选定愿望清单的项目列表。同样,我会用滑动删除动作删除整个愿望清单。UITableViewCell中的Swift UICollectionView无法正常工作

这里我的问题是,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 
} 
} 

这里是我的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 
     } 
    } 
+0

只是一个猜测,但不应该将集合视图的代表是在您添加集合视图协议视图控制器设置?并设置数据源并在那里委托?我看到你已经添加了一个扩展,尽管可能不是。 –

+0

我正在关注几个这样做的博客,https://contentpedlar.wordpress.com/2016/10/22/uicollectionview-in-uitableview/ – markhorrocks

+0

也许是因为您正在主线程上进行Web请求,阻止了用户界面及其集合视图的更新,因此为什么你没有得到函数调用。如果你评论你的Alamofire代码会发生什么。 –

回答

1

它看起来并不像你加入您的收藏欣赏到在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之内。

+0

这也没有帮助。没有任何集合视图函数被触发。 – markhorrocks

+0

您可以设置集合视图的背景颜色,并确保它显示在表格单元格中吗?另外,你是否在'awakeFromNib'中设置了一个断点来确保它被调用? –

+0

tableViewCell没有被调用。 – markhorrocks

0

初始化被错误地放在awakeFromNib(),应该已经在

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