i have a UICollectionview that gets images form Parse.
I'm now trying to push to a detail view then I'm push on a image in the UICollectionView.
Do anybody have any idea on how to do this?
Here is my code:
viewcontroller:
import UIKit
import Parse
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
#IBOutlet var collectionView: UICollectionView?
var imageFilesArray:NSArray = NSArray()
var refreshControl: UIRefreshControl!
// var isAscending = true
override func viewDidLoad() {
super.viewDidLoad()
self.refreshControl = UIRefreshControl()
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl.addTarget(self, action: Selector("imageRefresh"), forControlEvents: UIControlEvents.ValueChanged)
self.refreshControl.tintColor = UIColor.whiteColor()
self.collectionView?.addSubview(refreshControl)
// Do any additional setup after loading the view, typically from a nib.
//let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
//layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 20, right: 10)
//layout.itemSize = CGSize(width: 150 , height: 150)
// collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView!.dataSource = self
collectionView!.delegate = self
collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "imageCell")
collectionView?.alwaysBounceVertical = true
//collectionView!.backgroundColor = UIColor.whiteColor()
self.view.addSubview(collectionView!)
parseQuery()
}
func parseQuery() {
//query
var query = PFQuery(className: "photo")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock{
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
self.imageFilesArray = objects
//println(self.imageFilesArray)
}
self.collectionView?.reloadData()
}
}
func imageRefresh() {
parseQuery()
self.refreshControl.endRefreshing()
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
println(self.imageFilesArray.count)
return self.imageFilesArray.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imageCell", forIndexPath: indexPath) as CollectionViewCell
cell.backgroundColor = UIColor.blackColor()
let imageObject = self.imageFilesArray.objectAtIndex(indexPath.row) as PFObject
let imageFile = imageObject.objectForKey("imageFile") as PFFile
imageFile.getDataInBackgroundWithBlock{
(data: NSData!, error: NSError!) -> Void in
if error == nil {
cell.imageView.image = UIImage(data: data)
}
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
collectionviewcell:
import UIKit
class CollectionViewCell: UICollectionViewCell {
#IBOutlet var imageView: UIImageView!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
imageView.contentMode = UIViewContentMode.ScaleToFill
contentView.addSubview(imageView)
}
}
Detailviewcontroller:
import UIKit
import Parse
class photoDetailViewController: UIViewController {
#IBOutlet var detailImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
i hope somebody can help on on how to write the code to push to the detail view, and show the same image that was pressed.
--
OlePetter
Update your didSelectItemAtIndexPath method,
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
var detailsViewController: DetailsViewController = DetailsViewController(nibName:"DetailsViewController",bundle:nil)
self.presentViewController(detailsViewController, animated: true) { () -> Void in
}
}
Note: In place of DetailsViewController write your own Details ViewController's name. and write you own nibName.
Related
I have a viewController with a collectionView inside of it. I'm pretty sure that I have configured everything right yet it is not rendering any cells. I have added the appropriate delegates and data sources and double checked to see if the data is loading and it is but cells are not being populated
import UIKit
import UIKit
import Alamofire
import AlamofireNetworkActivityIndicator
import SwiftLocation
import CoreLocation
import AMScrollingNavbar
class NewHomeFeedControllerViewController: UIViewController {
let detailView = EventDetailViewController()
var allEvents = [Event]()
let customCellIdentifier1 = "customCellIdentifier1"
var grideLayout = GridLayout(numberOfColumns: 2)
let refreshControl = UIRefreshControl()
var newHomeFeed: NewHomeFeedControllerViewController?
let paginationHelper = PaginationHelper<Event>(serviceMethod: PostService.showEvent)
lazy var dropDownLauncer : DropDownLauncher = {
let launcer = DropDownLauncher()
launcer.newHomeFeed = self
return launcer
}()
// 1 IGListKit uses IGListCollectionView, which is a subclass of UICollectionView, which patches some functionality and prevents others.
let collectionView: UICollectionView = {
// 2 This starts with a zero-sized rect since the view isn’t created yet. It uses the UICollectionViewFlowLayout just as the ClassicFeedViewController did.
let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
// 3 The background color is set to white
view.backgroundColor = UIColor.white
return view
}()
func handleDropDownMenu(){
dropDownLauncer.showDropDown()
}
func configureCollectionView() {
// add pull to refresh
refreshControl.addTarget(self, action: #selector(reloadHomeFeed), for: .valueChanged)
collectionView.addSubview(refreshControl)
}
func reloadHomeFeed() {
self.paginationHelper.reloadData(completion: { [unowned self] (events) in
self.allEvents = events
if self.refreshControl.isRefreshing {
self.refreshControl.endRefreshing()
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
})
}
func categoryFetch(dropDown: DropDown){
navigationItem.title = dropDown.name
paginationHelper.category = dropDown.name
configureCollectionView()
reloadHomeFeed()
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
collectionView.contentInset = UIEdgeInsetsMake(15, 0, 0, 0)
navigationItem.title = "Home"
collectionView.dataSource = self
collectionView.delegate = self
collectionView.collectionViewLayout = grideLayout
collectionView.reloadData()
collectionView.register(CustomCell.self, forCellWithReuseIdentifier: customCellIdentifier1)
// self.navigationItem.hidesBackButton = true
let backButton = UIBarButtonItem(image: UIImage(named: "menu"), style: .plain, target: self, action: #selector(handleDropDownMenu))
self.navigationItem.leftBarButtonItem = backButton
configureCollectionView()
reloadHomeFeed()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let navigationController = self.navigationController as? ScrollingNavigationController {
navigationController.followScrollView(self.collectionView, delay: 50.0)
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let navigationController = navigationController as? ScrollingNavigationController {
navigationController.stopFollowingScrollView()
}
}
func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
if let navigationController = navigationController as? ScrollingNavigationController {
navigationController.showNavbar(animated: true)
}
return true
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
grideLayout.invalidateLayout()
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension NewHomeFeedControllerViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return allEvents.count
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let customCell = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier1, for: indexPath) as! CustomCell
let imageURL = URL(string: allEvents[indexPath.item].currentEventImage)
print(imageURL ?? "")
customCell.sampleImage.af_setImage(withURL: imageURL!)
return customCell
}
}
extension NewHomeFeedControllerViewController: UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.item == 0 || indexPath.item == 1 {
return CGSize(width: view.frame.width, height: grideLayout.itemSize.height)
}else{
return grideLayout.itemSize
}
}
}
Any idea what could be going on?
Sorry you guys forgot to add this
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
}
Haha thanks for the help
I am trying to segue an array of images from a UICollectionViewController to a UITableViewController with static cells. The setup is that when a user presses a cell in the collection view controller, the UIImage in that cell segues to the UIImageView in the table view controller.
The problem is that the image is not appearing in the UITableViewController's UIImageView.
I think that the UIImage is not being passed to the UIImageView in the UITableViewController.
Here is my relevant UICollectionViewController code:
import UIKit
private let reuseIdentifier = "Cell"
class AddImageCollectionViewController: UICollectionViewController {
var mainImages = ["cup", "transport", "beach", "weather", "gear", "money", "technology-1", "web", "people", "nature", "draw", "technology", "screen", "shop", "arrow"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return mainImages.count
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let screenSize = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width / 3
let screenHeight = screenWidth
let size = CGSize(width: screenWidth, height: screenHeight)
return size
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! AddImageCollectionViewCell
// Configure the cell
cell.mainImageView.image = UIImage(named: mainImages[indexPath.row])
return cell
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
collectionView?.reloadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "nextStep" {
if let indexPaths = collectionView?.indexPathsForSelectedItems() {
let destinationViewController = segue.destinationViewController as! AddTableViewController
//let photoViewController = destinationViewController.viewControllers[0] as! PhotoViewController
destinationViewController.imageName = mainImages[indexPaths[0].row]
}
}
}
}
Here is my relevant UITableViewController code:
import UIKit
import CoreData
class AddTableViewController: UITableViewController {
// MARK: - Table view data source
#IBOutlet var photoImageView:UIImageView!
var content:Agenda!
var imageName:String = ""
override func viewDidLoad() {
super.viewDidLoad()
photoImageView.image = UIImage(named: imageName)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
After selecting my cell in the Collection View Controller in the simulator, I get the following error message in the console:
CUICatalog: Invalid asset name supplied:
I have a UICollectionView that displays 12 images. The images are not fitting in the cells, they are being cropped, but I want them to fit in the cells without being cropped.
The code that should make the image scale to fit is:
cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit
cell.imageView.image = UIImage(named: name)
Here is my code for the whole viewController class and screenshot:
import UIKit
class DressingRoomViewController:
UIViewController,
UICollectionViewDelegateFlowLayout,
UICollectionViewDataSource {
#IBOutlet weak var collectionView: UICollectionView!
let identifier = "cellIdentifier"
let dataSource = DataSource()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
}
override func viewDidAppear(animated: Bool) {
// Notes on the equation to get the cell size:
// cells per row = 6
// cell spacing = 10
// collectionView.layout.inset = 20 (10 left, 10 right)
let cellSize = (collectionView.collectionViewLayout
.collectionViewContentSize().width - 20) / 6 - 10
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets( top: 20,
left: 10,
bottom: 10,
right: 10)
layout.itemSize = CGSize(width: cellSize, height: cellSize)
collectionView.collectionViewLayout = layout
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue( segue: UIStoryboardSegue,
sender: AnyObject?) {
if (segue.identifier == "dressingRoom2MyOutfits") {
let myOutfitsViewController = segue.destinationViewController
as! MyOutfitsViewController
}
}
}
// MARK:- UICollectionViewDataSource Delegate
extension DressingRoomViewController : UICollectionViewDataSource {
func numberOfSectionsInCollectionView(
collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return 12
}
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
identifier,forIndexPath:indexPath) as! FruitCell
let fruits: [Fruit] = dataSource.fruits
let fruit = fruits[indexPath.row]
let name = fruit.name!
cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit
cell.imageView.image = UIImage(named: name)
return cell
}
}
EDIT: Here is the FruitCell class, just in case you were wondering.
class FruitCell: UICollectionViewCell {
#IBOutlet weak var imageView: UIImageView!
}
A UIImageView that has been placed in a UICollectionViewCell from the interface builder, will not have any knowledge of a UICollectionViewFlowLayout that has been initialised programmatically. So the layout.sectionInset that I had set, was making the UICollectionViewCells smaller, and even when the UIImageView created in interface builder was constrained to the margins of the UICollectionViewCell, the UIImageView was not resizing to go smaller.
The solution was to initialise the UIImageView programmatically and set the size to be the size of the cell taking into account the cell spacing.
Here is the code:
import UIKit
class DressingRoomViewController:
UIViewController,
UICollectionViewDelegateFlowLayout,
UICollectionViewDataSource {
#IBOutlet weak var collectionView: UICollectionView!
let identifier = "cellIdentifier"
let dataSource = DataSource()
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
let cellSpacing: CGFloat = 2
let cellsPerRow: CGFloat = 6
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
}
override func viewDidAppear(animated: Bool) {
let cellSize = (collectionView.collectionViewLayout
.collectionViewContentSize().width / cellsPerRow) - (cellSpacing)
layout.itemSize = CGSize(width: cellSize, height: cellSize)
layout.minimumInteritemSpacing = cellSpacing
layout.minimumLineSpacing = cellSpacing
collectionView.collectionViewLayout = layout
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue( segue: UIStoryboardSegue,
sender: AnyObject?) {
if (segue.identifier == "dressingRoom2MyOutfits") {
let myOutfitsViewController = segue.destinationViewController
as! MyOutfitsViewController
}
}
}
// MARK:- UICollectionViewDataSource Delegate
extension DressingRoomViewController : UICollectionViewDataSource {
func numberOfSectionsInCollectionView(
collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return 12
}
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
identifier,forIndexPath:indexPath) as! FruitCell
let fruits: [Fruit] = dataSource.fruits
let fruit = fruits[indexPath.row]
let name = fruit.name!
var imageView :UIImageView
imageView = UIImageView(frame:CGRectMake( 0,
0,
(collectionView.collectionViewLayout
.collectionViewContentSize().width / cellsPerRow)
- (cellSpacing),
(collectionView.collectionViewLayout
.collectionViewContentSize().width / cellsPerRow)
- (cellSpacing)))
imageView.contentMode = UIViewContentMode.ScaleAspectFit
imageView.image = UIImage(named: name)
imageView.backgroundColor = UIColor.redColor()
cell.addSubview(imageView)
return cell
}
}
EDIT: I was able to crop off the empty space at the bottom of the UICollectionView by creating an outlet for the height constraint ( control + drag height constraint in interface builder onto viewController swift file) calling it heightConstraint, and then at the bottom of viewDidAppear added these two lines of code:
self.heightConstraint.constant = collectionView.contentSize.height
self.view.layoutIfNeeded()
So to show you the result with a white background on the UICollectionView and a red background on the UIImageViews, here is the result (also works on all other device sizes):
I have a requirement to use collection view in table view cell but , i am getting a bank table view cell can anybody please tell me what i am missing
![My storyboard]
contains
View,
Tableview,
TableViewCell,
Contentview,
collectionview,
collectionviewcell.
inside that
imageview and label to display the data
i have three class
1st one customcollectionview
class CustomCollectionViewCell: UICollectionViewCell {
#IBOutlet var AssetImage: UIImageView!
#IBOutlet var assetLabeldesc: UILabel!
override init(frame: CGRect)
{
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
}
}
2)
class CustomTableViewCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate {
#IBOutlet var AssetCollectionView: UICollectionView!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
super.init(coder: aDecoder)
}
var folderCount:Int?
{
didSet(value)
{
}
}
override func awakeFromNib() {
super.awakeFromNib()
var aFlowLayout : UICollectionViewFlowLayout = UICollectionViewFlowLayout()
aFlowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
aFlowLayout.itemSize = CGSizeMake(60.0, 90.0)
aFlowLayout.minimumLineSpacing = 10.0
aFlowLayout.minimumInteritemSpacing = 0.0
aFlowLayout.sectionInset = UIEdgeInsetsMake(2, 9, 0, 10)
AssetCollectionView.collectionViewLayout = aFlowLayout
AssetCollectionView.registerClass(CustomCollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
var cNib:UINib? = UINib(nibName: "CustomCollectionViewCell", bundle: nil)
AssetCollectionView.registerNib(cNib, forCellWithReuseIdentifier: "CollectionViewCell")
AssetCollectionView.frame = self.bounds
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
class func CreateCustomCell() -> CustomTableViewCell
{
var nibElements: Array = NSBundle.mainBundle().loadNibNamed("CustomTableViewCell", owner: self, options: nil)
var item: AnyObject?
for item in nibElements
{
if item is UITableViewCell
{
return item as CustomTableViewCell
}
}
return item as CustomTableViewCell
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
var cell :CustomCollectionViewCell? = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as? CustomCollectionViewCell
//hear u can modify which image to be displayed in the collection view cell
let imageNameString = "Logo.png"
let front = UIImage(named: imageNameString)
cell?.AssetImage.backgroundColor = UIColor.orangeColor()
cell?.AssetImage.image = front
cell?.assetLabeldesc.text = "Card:\(indexPath.row)"
return cell!
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return folderCount!
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
3)
class AssetViewController: UIViewController,UITableViewDataSource,UITableViewDelegate
{
var cardCountArray:[Int] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
cardCountArray = [5,15,6,12,7,10]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return cardCountArray.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell:CustomTableViewCell? = tableView.dequeueReusableCellWithIdentifier("CELL") as? CustomTableViewCell;
if(cell == nil)
{
cell = CustomTableViewCell.CreateCustomCell()
}
cell?.folderCount = cardCountArray[indexPath.section]
cell?.AssetCollectionView.reloadData()
cell?.clipsToBounds = true
return cell!;
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 100.0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var headerView:UIView = UIView(frame: CGRectMake(0, 0, tableView.bounds.size.width, 70.0))
var labelTitle:UILabel = UILabel(frame: CGRectMake(0, 0, tableView.bounds.size.width, 35))
var descriptionTitle:UILabel = UILabel(frame: CGRectMake(0, 20,tableView.bounds.size.width , 30))
headerView.addSubview(labelTitle)
headerView.addSubview(descriptionTitle)
labelTitle.text = "GroupName:\(section)"
descriptionTitle.text = "Description \(cardCountArray[section])"
return headerView
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50.0
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}``
*/
}
Can anybody tell me what am missing?
It appears you are adding the subview for some elements but not for your collectionView:
I see the views added for the labels:
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
headerView.addSubview(labelTitle)
headerView.addSubview(descriptionTitle)
You will need to add the collection view as well. You can do it here so it is added to every cell:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:CustomTableViewCell? = tableView.dequeueReusableCellWithIdentifier("CELL") as? CustomTableViewCell;
I approached this without using addSubview on another project. In my case I initiated the
collectionView.datasource = self
collectionView.delegate = self
I posted a similar question recently and someone responded with an approach that may help you. UICollectionView cells with Images inside UITableView prototype
I have two classes CustomSwipOut which is a subclass of UIView and ViewController subclass of UIViewController. The callback method of delegate is not firing in ViewController class from didSelectRowAtIndexPath delegate method of table view defined in CustomSwipeOut. I have done optional binding in ViewController class as var a = CustomSwipeOut(); a.delegate = ViewController()
protocol SendIndexDelegate{
func sendIndex(Int);
}
class CustomSwipeOut: UIView , UITableViewDataSource , UITableViewDelegate {
var label: UILabel = UILabel()
var myNames = ["item1","item2","item3"]
var delegate : SendIndexDelegate?
override init()
{
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.addCustomView()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addCustomView()
{
//add blank subview to the view
var blankView : UIView = UIView(frame: CGRectMake(0, 0, 300, 100))
blankView.backgroundColor = UIColor.greenColor()
self.addSubview(blankView)
//creating a tableview programmatically
var tblView : UITableView = UITableView()
tblView.frame = CGRectMake(0, 100, 300, 200)
self.addSubview(tblView)
tblView.delegate = self
tblView.dataSource = self
tblView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell")
}
//pragma mark- table view data source methods
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell") as UITableViewCell
cell.textLabel?.text = self.myNames[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.myNames.count
}
//pragma mark - table view delegate methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var row = indexPath.row
if let temp = self.delegate {
delegate?.sendIndex(row)
}else{
println("optional value contains nill value")
}
}
//ViewController Class
class ViewController: UIViewController , SendIndexDelegate {
var myView :UIView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var a = CustomSwipeOut()
a.delegate = ViewController()
let rect: CGRect = CGRect (x: self.view.frame.size.width, y :50 , width: self.view.frame.size.width-100, height: self.view.frame.size.height-100)
self.myView = CustomSwipeOut(frame : rect )
self.view.addSubview(self.myView)
//optional chaining
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func showSideMenu() {
UIView.animateWithDuration(0.2, animations:{
self.myView.frame = CGRectMake(100, 50,self.view.frame.size.width-100,self.view.frame.size.height-100)
} )
}
//delegate method
func sendIndex(row : Int)
{
switch row {
case 0:
println("index o clicked")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("MoneySum") as UIViewController
self.presentViewController(vc, animated: true, completion: nil)
println("index 2 clicked")
...
default:
println("no index")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let rect: CGRect = CGRect (x: self.view.frame.size.width, y :50 , width: self.view.frame.size.width-100, height: self.view.frame.size.height-100)
var a = CustomSwipeOut(frame : rect)
a.delegate = self
self.myView = a
self.view.addSubview(self.myView)
//optional chaining
}