swift custom uitextviewcell label always nil - ios

i'm stuck here since two days ago, and cant find how to manage this..
I have an uitableview, with an array of custom cells and sections, here's what i want to do:
Section 1: just a row with a label inside
Section 2: a datepicker (i used DVDatePickerTableViewCell class for this)
here's the code for the table view
import UIKit
class DettagliRichiestaTVC: UITableViewController {
//sections contiene le sezioni
let sections: NSArray = ["Stato", "Data", "Priorità", "Richiesta", "Risposta"]
//cells contiene tutte le righe della tabella, un 2D array
var cells:NSArray = []
var stato:String = "Completato"
#IBOutlet weak var statoLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// statoLabel.text = stato
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44
// Cells is a 2D array containing sections and rows.
var cellStato = cellDettagli(style: UITableViewCellStyle.Default, reuseIdentifier: "cellStato")
cellStato.label?.text = "Ciao"
cells = [
[cellStato],
[DVDatePickerTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)]
]
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func selectedStato(segue:UIStoryboardSegue) {
let statoRichiesteTVC = segue.sourceViewController as StatoRichiesteTVC
if let selectedStato = statoRichiesteTVC.selectedStato {
statoLabel.text = selectedStato
stato = selectedStato
}
self.navigationController?.popViewControllerAnimated(true)
}
// MARK: - Table view data source
/*
// 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.
}
*/
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var headerFrame:CGRect = tableView.frame
var title = UILabel(frame: CGRectMake(10, 10, 100, 20))
title.font = UIFont.boldSystemFontOfSize(12.0)
title.text = self.sections.objectAtIndex(section) as? String
title.textColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
var headerView:UIView = UIView(frame: CGRectMake(0, 0, headerFrame.size.width, headerFrame.size.height))
headerView.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.8)
headerView.addSubview(title)
return headerView
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var cell = self.tableView(tableView, cellForRowAtIndexPath: indexPath)
if (cell.isKindOfClass(DVDatePickerTableViewCell)) {
return (cell as DVDatePickerTableViewCell).datePickerHeight()
}
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return cells.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cells[section].count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return cells[indexPath.section][indexPath.row] as UITableViewCell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var cell = self.tableView(tableView, cellForRowAtIndexPath: indexPath)
if (cell.isKindOfClass(DVDatePickerTableViewCell)) {
var datePickerTableViewCell = cell as DVDatePickerTableViewCell
datePickerTableViewCell.selectedInTableView(tableView)
}
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//println(segue.identifier)
if segue.identifier == "SavePlayerDetail" {
}
if segue.identifier == "SelezionaStatoRichiesta" {
let statoRichiesteTVC = segue.destinationViewController as StatoRichiesteTVC
statoRichiesteTVC.selectedStato = stato
}
}
}
and here's the custom cell class
import UIKit
class cellDettagli: UITableViewCell {
#IBOutlet weak var label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func loadItem(#Label: String) {
label.text = Label
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init(coder aDecoder: NSCoder) {
//fatalError("init(coder:) has not been implemented")
super.init(coder: aDecoder)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
if i set cellStato.label?.text = "Ciao" , it crashes saying "fatal error: unexpectedly found nil while unwrapping an Optional value" .
I created also the .xib file and assigned that to cellDettagli class.
I always get that error.
How can i set the values of this label, and the date of the datepicker row?
Thank you

I made it work using this:
var cell:cellDettagli? = tableView.dequeueReusableCellWithIdentifier("cellDettagli") as? cellDettagli
if (cell==nil){
var nib:NSArray=NSBundle.mainBundle().loadNibNamed("cellDettagli", owner: self, options: nil)
cell = nib.objectAtIndex(0) as? cellDettagli
}
inside my cellForRowAtIndexPath.
Thank you Alexander for your help! I already use static cells and storyboards...!

You're creating cells using the designated initialiser, which means the views that you've added in the nib won't be there at runtime. You will need to register your nib with the tableview first using registerNib:forCellReuseIdentifier:, then dequeue cells accordingly using dequeueReusableCellWithIdentifier:forIndexPath:.
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/index.html
Since it looks like you're using static cells, you might be better off using a storyboard with "Static Cells" content type on your table view instead of "Dynamic Prototypes".
For more information on static cells, see the docs https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/TableView_iPhone/CreateConfigureTableView/CreateConfigureTableView.html

Related

Storyboard initial viewcontroller doesn't appear

My app is in swift using story board. After launch file my app start the initial view controller the one I have already set the entry point. But suddenly my app doesn't appear the initial viewcontroller after the Launching screen.but if I set the entry point to another view controller its appear. The first viewcontroller viewdidload and all other UITableView delegates and datasource are running when Idebug but the screen doesnt come it just keep staying on my launch file.
What would be the reason for this? Please help me.
Thanks
UPDATE
import UIKit
class SubscriptionViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tblSettings: UITableView!
#IBOutlet weak var vwTitle: UIView!
var mutableDictionary :[String]=["Business","News","Sports","Entertainment","Crime","Politics"]
var imageView = UIImageView.init(frame: CGRectMake(0, 0, 20, 20))
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tblSettings.backgroundColor=UIColor.clearColor()
tblSettings.delegate=self
tblSettings.dataSource=self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mutableDictionary.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("SettingsCell") as! SettingsTableViewCell!
if cell == nil
{
//tableView.registerNib(UINib(nibName: "UICustomTableViewCell", bundle: nil), forCellReuseIdentifier: "UICustomTableViewCell")
tableView.registerClass(SettingsTableViewCell.classForCoder(), forCellReuseIdentifier: "SettingsCell")
cell = SettingsTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "SettingsCell")
}
cell.backgroundColor=UIColor.clearColor()
// Custom view options
let image=UIImage.init(named: "SettingsUnChecked")
imageView.image=image
cell.accessoryType = UITableViewCellAccessoryType.None
cell.accessoryView = imageView//UIButton(frame: CGRectMake(0, 0, 20, 20))
cell.accessoryView!.backgroundColor = UIColor.clearColor()
if let label = cell.lblName{
label.text = mutableDictionary[indexPath.row]
label.textColor=UIColor.whiteColor()
}
return cell
}
/*
// 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.
}
*/
}

UIButton inside custom UITableViewCell causes button to be selected in multiple cells

The goal of the UITableView is to display names with a custom styled checkbox beside it. But somehow when I tap the checkbox, multiple checkboxes in the UITableView get selected.
I've googled and implemented multiple solutions from different questions but none of them seem to work.
Custom UITableViewCell
import UIKit
class NameTableViewCell: UITableViewCell {
var name = UILabel()
let checkboxImage_unchecked = UIImage(named: "cellViewCheckbox_unchecked")
let checkboxImage_checked = UIImage(named: "cellViewCheckbox_checked")
let checkbox:UIButton
weak var delegate:HandleCellInteractionDelegate?
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
self.checkbox = UIButton(frame: CGRectMake(35, 16, self.checkboxImage_unchecked!.size.width/2, self.checkboxImage_unchecked!.size.height/2))
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.transparant()
self.checkbox.setBackgroundImage(self.checkboxImage_unchecked, forState: .Normal)
self.checkbox.setBackgroundImage(self.checkboxImage_checked, forState: .Selected)
self.name = UILabel(frame: CGRectMake(97,18,200, 30))
self.addSubview(self.name)
self.addSubview(self.checkbox)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func checkboxPushed(sender:AnyObject){
self.checkbox.selected = !self.checkbox.selected
self.delegate?.didPressButton(self)
}
In the protocol I declare a method didPressButton as a callback for when the button is pressed (the delegate needs to implement it)
Protocol
import UIKit
protocol HandleCellInteractionDelegate:class {
func didPressButton(cell:NameTableViewCell)
}
The ViewController
import UIKit
class NameViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, HandleCellInteractionDelegate{
var nameView:NameView {
get {
return self.view as! NameView
}
}
var names:[Name]?
var firstLetters:[String]?
let cellIdentifier = "nameCell"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//self.view.backgroundColor = UIColor.darkSalmon()
}
override func loadView() {
let bounds = UIScreen.mainScreen().bounds
self.view = NameView(frame: bounds)
if(NSUserDefaults.standardUserDefaults().objectForKey("gender") !== nil){
self.loadJSON()
self.getFirstLetters();
self.nameView.tableView.delegate = self;
self.nameView.tableView.dataSource = self;
self.nameView.tableView.registerClass(NameTableViewCell.classForCoder(), forCellReuseIdentifier: "nameCell")
self.nameView.tableView.separatorStyle = .None
self.nameView.tableView.rowHeight = 66.5 }
}
func loadJSON(){
let path = NSBundle.mainBundle().URLForResource("names", withExtension: "json")
let jsonData = NSData(contentsOfURL: path!)
self.names = NamesFactory.createFromJSONData(jsonData!, gender: NSUserDefaults.standardUserDefaults().integerForKey("gender"))
}
func getFirstLetters(){
var previous:String = ""
for name in self.names! {
let firstLetter = String(name.name.characters.prefix(1))
if firstLetter != previous {
previous = firstLetter
self.firstLetters?.append(firstLetter)
print(firstLetter)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (self.names!.count)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return nameCellAtIndexPath(indexPath)
}
func nameCellAtIndexPath(indexPath:NSIndexPath) -> NameTableViewCell {
let cell = self.nameView.tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! NameTableViewCell
self.setNameForCell(cell, indexPath: indexPath)
cell.delegate = self;
cell.checkbox.addTarget(cell, action: "checkboxPushed:", forControlEvents: .TouchUpInside)
return cell
}
func setNameForCell(cell:NameTableViewCell, indexPath:NSIndexPath) {
let item = self.names![indexPath.row] as Name
cell.name.text = item.name
}
func didPressButton(cell: NameTableViewCell) {
print(cell)
}
}
What am I doing wrong & how can I fix it?
You must have to save the check box state. Add one more attribute say checkboxStatus to your Model(Name).I hope you will have indexpath.row.
After this line in nameCellAtIndexPath
cell.delegate = self;
set the tag like this
cell.tag = indexPath.row;
In the delegate method,
func didPressButton(cell: NameTableViewCell) {
print(cell)
let item = self.names![cell.tag] as Name
item.checkboxstatus = cell.checkbox.selected
}
Just one crucial change,
func nameCellAtIndexPath(indexPath:NSIndexPath) -> NameTableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! NameTableViewCell
self.setNameForCell(cell, indexPath: indexPath)
cell.delegate = self;
cell.tag = indexPath.row;
cell.checkbox.addTarget(cell, action: "checkboxPushed:", forControlEvents: .TouchUpInside)
let item = self.names![cell.tag] as Name
cell.checkbox.selected = item.checkboxstatus
return cell
}
Cheers!
This happens because the UITableViewCell are being reused.
You changed the cell when you press the checkbox, you need to keep track of that in your data source model.
In cellForRowAtIndexPath you have to add a condition to check if that checkbox was checked or not. Then you display the appropriate view accordingly.
Edit:
In your example you need to check in nameCellAtIndexPath if the checkbox is checked or not and then display it correct.

Display custom UITableViewCell from an array of cells

I have an UIViewController that creates a custom UITableViewCell and insert it into an array. Then I've a UITableViewController and I want to show cells from previous array. The problem is that in tableView(tableView:cellForRowAtIndexPath) I don't want to use dequeueReusableCellWithIdentifier because I just want to get the cells from the array and use them.
Unfortunately this doesn't work. I read dequeueReusableCellWithIdentifier permits to save in memory only the necessary cells.
I'm thinking about a method to "push" my custom cells in that queue but I can't find anything. So at the end I'm not able to show my custom cells.
Note: I can't obtain the cell using dequeueReusableCellWithIdentifier and than set each properties because one of them is a UIProgressView and it's updated within my custom cell class so I need to display that cell.
This is the code within the UIViewController which create the custom cell and set it into the array:
//here I create my custom cell (DownloadTVCell)
let cell = DownloadTVCell(style: UITableViewCellStyle.Default, reuseIdentifier: "DownloadRootTVC_IDcell")
cell.nomeFileInDownloadLabel.text = nomeCompletoMp3
//this is a method in DownloadTVCell that starts a download task
cell.createDownloadTask()
//here i got the navigationController in order to obtain the instance of
//the UITableViewController. In this method when a user tap on the
//UITableViewController it's already instantiated
let nc = self.tabBarController!.viewControllers![1] as! UINavigationController
let drtvc = nc.topViewController as! DownloadRootTVC
//now drtvc is the instance of DOwnloadRootTVC which is my custom UITableViewController
//add the cell to the array
drtvc.listOfCellsDownlaod.append(cell)
This is my custom cell:
class DownloadTVCell: MGSwipeTableCell, NSURLSessionDownloadDelegate {
//******************************************************************
// IBOUtlet
//******************************************************************
#IBOutlet var nomeFileInDownloadLabel: UILabel!
#IBOutlet var quantitaScaricataLabel: UILabel!
#IBOutlet var progressView: UIProgressView!
private var downloadTask: NSURLSessionDownloadTask?
//******************************************************************
// METODI
//******************************************************************
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
log("ACTION", text: "Metodo chiamato")
build()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
log("ACTION", text: "Metodo chiamato")
build()
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
private func build() {
self.nomeFileInDownloadLabel = UILabel()
self.quantitaScaricataLabel = UILabel()
self.progressView = UIProgressView()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
//here there is some logic for download
...
}
And finally this is my custom UITableView:
class DownloadRootTVC: UITableViewController {
//******************************************************************
// PROPRIETA' GENERICHE
//******************************************************************
var listOfCellsDownlaod = [DownloadTVCell]()
//******************************************************************
// METODI
//******************************************************************
override func viewDidLoad() {
log(text: "self.listOfCellsDownlaod.count: \(self.listOfCellsDownlaod.count)")
self.tableView.delegate = self
self.tableView.dataSource = self
self.refreshControl?.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadTableData:", name: "reload", object: nil)
//self.tableView.registerClass(DownloadTVCell.self, forCellReuseIdentifier: "DownloadRootTVC_IDcell")
super.viewDidLoad()
}
func refresh(sender:AnyObject) {
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
func reloadTableData(notification: NSNotification) {
tableView.reloadData()
}
override func viewDidAppear(animated: Bool) {
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.listOfCellsDownlaod.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCellWithIdentifier("DownloadRootTVC_IDcell", forIndexPath: indexPath) as! DownloadTVCell
//I just want to return my custom cell
return self.listOfCellsDownlaod[indexPath.row]
}
}
Instead of adding UITableViewCells to your array you should probably add only the cell identifiers and then dequeue the cells in cellForRowAtIndexPath and do the set up there. If you can't retrieve the information to populate the cells in cellForRowAtIndexPath, then create a class or object to save the cell identifiers together with all the info you need to populate the cells (texts for labels, image file names for image views, etc).
Remember that table view cells are view objects and you should not include logic in view objects. Put all the logic into a separate object and then just fill the cells as needed.

UICollectionView in UItableView Getting only empty tableview , what i have missed?

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

Delegate didSet property of UIView not being called inside custom UITableViewCell

I've been banging my head on the desk for the past 2 hours trying to figure this out so any help will be greatly appreciated.
I'm using CVCalendar (the develop branch) and I'm trying to place the CalendarView inside a custom UITableViewCell so I can make it look something like this:
The problem I'm facing is that it doesn't set the delegate property when I call self.calendarView.calendarDelegate = self inside the custom UITableViewCell
I know it's not being set because I've placed a println inside the delegate didSet property that's not being outputted.
Here is the CalendarViewDelegate outlet inside the CalendarView
// MARK: - Calendar View Delegate
#IBOutlet weak var calendarDelegate: AnyObject? {
set {
if let calendarDelegate = newValue as? Delegate {
delegate = calendarDelegate
println("delegate did set property called")
}
}
get {
return delegate
}
}
Here is my code for the custom UITableViewCell I'm working with.
import UIKit
class CalendarCell: UITableViewCell {
var calendarView: CVCalendarView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.redColor()
selectionStyle = .None
self.calendarView = CVCalendarView(frame: self.frame)
self.calendarView.calendarDelegate = self
self.calendarView.calendarAppearanceDelegate = self
self.calendarView.animatorDelegate = self
contentView.addSubview(calendarView)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.calendarView.commitCalendarViewUpdate()
}
}
Here is my UITableViewController code:
import UIKit
class CalendarTableViewController: UITableViewController {
#IBOutlet var myTableView: UITableView!
var items = ["Apple", "Banana"];
override func viewDidLoad() {
super.viewDidLoad()
self.myTableView.registerClass(CalendarCell.self, forCellReuseIdentifier: NSStringFromClass(CalendarCell))
self.myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
self.myTableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func creatHeaderCell() -> UITableViewCell {
var headerCell = self.myTableView.dequeueReusableCellWithIdentifier(NSStringFromClass(CalendarCell)) as! CalendarCell
return headerCell
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (indexPath.section == 0) {
return 300
}
return 44
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (section) {
case 0:
return 1
default:
return items.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.section == 0) {
return self.creatHeaderCell()
}
let cell = self.myTableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel!.text = "Thomas"
// Configure the cell...
return cell
}
}
Your println statement is probably not reached because your if condition if let calendarDelegate = newValue as? Delegate is not true because what you pass in as calenderDelegate is a CalenderCell, not a Delegate or CVCalendarViewDelegate (typealias).
Additionally your CalendarCell does not conform to CVCalendarViewAppearanceDelegate and CVCalendarViewAnimatorDelegate.
You have to make your cell conform to those protocols to be able to set them as delegates.

Resources