Custom UITableViewCell using xib and autolayout doesn`t show correctly in several cells on the top - ios

I used custom UITableViewCell named "SCTableViewCell" and linked with "CustomCell.xib" and loading in "CenterViewController"
and when it runs, several cells on the top looks bad(like follow picture) and, after scroll down screen and up again(bad cells once disappear and appear again) it looks fine
it is custom cell class
SCTableViewCell.swift
class SCTableViewCell: UITableViewCell {
#IBOutlet weak var thumbnailImage : UIImageView!
#IBOutlet weak var titleLabel : UILabel!
#IBOutlet weak var descLabel : UILabel!
func loadItem(#title: String, desc: String, image: UIImage){
titleLabel.text = title
descLabel.text = desc
thumbnailImage.image = image
self.contentView.setTranslatesAutoresizingMaskIntoConstraints(true)
}
override func layoutSubviews() {
}
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
}
}
and CenterViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
//Setting Custom Tableview Cell
self.tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as SCTableViewCell
cell.loadItem(title: title!, desc: desc!, image: pic)
cell.updateConstraints()
return cell
}
console shows nothing....
please help me...

Oh!
I didn`t set up my cell height... ha...ha....
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 160
}
added in CenterViewController.swift and it works

Related

Table View items are not showing

I am new to iOS development.
I'm trying to display a list of items in my app using UITableView, but the items are not showing:
My View Controller:
class HistoryView: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
let cellReuseIdentifier = "cell"
#IBOutlet weak var noDataLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(HistoryTableViewCell.self, forCellReuseIdentifier: "historyCell")
tableView.delegate = self
tableView.dataSource = self
self.noDataLabel.isHidden=true
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "historyCell") as! HistoryTableViewCell
cell.nickname?.text = "name"
return cell
}
}
My Table View Cell:
class HistoryTableViewCell: UITableViewCell {
#IBOutlet weak var nickname: UILabel!
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
}
}
Any suggestions for what's going on?
condition 1:
if you are using prototype cells remove the line
tableView.register(HistoryTableViewCell.self, forCellReuseIdentifier:"historyCell")
and give cell identifier in the storyboard
condition 2:
if you are using xib file then register the cell like below:-
tableView.register(UINib(nibName: "HistoryTableViewCell", bundle: nil), forCellReuseIdentifier: "historyCell")
you need to register cell like this
tb.register(UINib(nibName: "HistoryTableViewCell", bundle: nil), forCellReuseIdentifier: "historyCell")
I saw #IBOutlet weak var nickname: UILabel!
in the class HistoryTableViewCell.
for table cells,
dequeueReusableCell and register, should called in pairs

Swift PickerView with custom tableViewCell.xib

I am messing around with swift and i am stuck in creating an UIPickerView connection with a custom TableViewCell.xib. The functionality i want is the following: when i press the switch button a pickerView appears that lets me select a month which will appear instead of the "Select Month" label. I don't really understand where should i create the outlets.
Cell Xib
Main StoryBoard
class TableViewCell: UITableViewCell {
#IBOutlet weak var leftImage: UIImageView!
#IBOutlet weak var label: UILabel!
#IBOutlet weak var rightImage: UIImageView!
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
}
func commonInit(_ imageName1: String, _ imageName2: String, text: String){
leftImage.image = UIImage(named: imageName1)
rightImage.image = UIImage(named: imageName2)
label.text = text
}
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let textData = ["Select Month"]
let datePicker = UIDatePicker()
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "UiTableView"
tableView.delegate = self
tableView.dataSource = self
let nibName = UINib(nibName: "TableViewCell", bundle: nil)
tableView.register(nibName, forCellReuseIdentifier: "tableViewCell")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return textData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as! TableViewCell
cell.commonInit("facebook", "twitter", text: textData[indexPath.item])
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 170
}
func createDatePicker(){
let toolBar = UIToolbar()
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil)
toolBar.setItems([doneButton], animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Open up the Cell Xib file and choose from the Menu, View>Assistand Editor>Show Assistant Editor. Once the Assistant Editor is open you can open the TableViewCell class. Control Drag from the 3 controls in the XIB in Interface builder to the corresponding entry in the file. Once over the entry such as #IBOutlet weak var leftImage: UIImageView!, it will highlight. Release the mouse and the connection will be established.
It is actually a little bit easier to not type the line with the outlet declaration in the class first. In this case, when you control drag from ID you position the mouse over an empty line and a dialog box appears where you can declare the outlet. It creates the connection at the same time.

Custom cell content doesn't show Swift

I want to create a custom table view. I have an UITableViewController:
class MainListView: UITableViewController{
var invoceList: [InvoceObject] = []
#IBOutlet var tbMain: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(CustomCell.self, forCellReuseIdentifier: "cell")
tbMain.delegate = self
self.tbMain.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.invoceList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.lblBuyerName?.text = self.invoceList[indexPath.row].BUYER_NAME
cell.lblDate?.text = self.invoceList[indexPath.row].CREATED_AT
cell.lblPriceGross?.text = self.invoceList[indexPath.row].PRICE + " " + self.invoceList[indexPath.row].CURRENCY
cell.backgroundColor = UIColor(white: 1, alpha: 0.5)
return cell
}
}
And my UITableViewCell class:
class CustomCell: UITableViewCell {
#IBOutlet weak var lblBuyerName: UILabel!
#IBOutlet weak var lblDate: UILabel!
#IBOutlet weak var lblPriceGross: UILabel!
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
}
}
After build I get an empty cells. I have a number of rows like invoceList.count, but there is no labels and it looks as empty table. What I'm doing wrong?
Since you are using UITableViewController there is an implicit tableView property with connected data source and delegate. You should use that to avoid confusion.
And delete the line self.tableView.register... if you are using prototype cells.
If the cell's contents are defined in a separate xib file, you need to register that, not the class - if you only register the class, the actual labels are not being created because the class itself does not create them.
//Replacing CustomCellNibName with the name of your xib file
tableView.register(UINib.init(nibName: "CustomCellNibName", bundle: nil), forCellReuseIdentifier: "Cell")
If the cell is being created in the storyboard as a prototype cell, you do not need to register it, but just associate the class with your cell in the storyboard file (under the identity inspector tab, Custom Class), and fill in the name you want to use (in this case, "Cell") under the Attributes inspector field Identifier.

dynamic tableview inside custom tableviewcell

I'm trying to create a tableview with custom cells that each one holds a tableview.
I want to show the inner tableview just when it have some data (most of the time it's empty). I've managed to display the cells but can't display their tableview if it's populated with data.
The problem also is that the cell height needs to be dynamic according to the amount of data to display.
The cell code:
class feedViewCell: UITableViewCell , UITableViewDataSource , UITableViewDelegate {
#IBOutlet var feedCellImage: UIImageView!
#IBOutlet var feedCellUserName: UILabel!
#IBOutlet var feedCellDate: UILabel!
#IBOutlet var feedCellComments: UILabel!
#IBOutlet var cardView: UIView!
#IBOutlet var repliesTableView: UITableView!
var repliesArray:[Reply] = []
#IBAction func addComment(sender: AnyObject) {
}
override func awakeFromNib() {
super.awakeFromNib()
var nib = UINib(nibName: "feedComment", bundle: nil)
repliesTableView.registerNib(nib, forCellReuseIdentifier: "commentCell")
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func layoutSubviews() {
cardSetup()
}
func cardSetup() {
cardView.layer.masksToBounds = false
cardView.layer.cornerRadius = 5
cardView.layer.shadowOffset = CGSizeMake(-0.2, 0.2)
cardView.layer.shadowRadius = 1
cardView.layer.shadowOpacity = 0.2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return repliesArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = repliesTableView.dequeueReusableCellWithIdentifier("commentCell", forIndexPath: indexPath) as CommentFeedCell
cell.commentCellUserName.text = repliesArray[indexPath.row].userName
return cell
}
}
And the Main controller code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var comment = comments[indexPath.row]
let cell: feedViewCell = tableView.dequeueReusableCellWithIdentifier("feedCell", forIndexPath: indexPath) as feedViewCell
cell.feedCellUserName.text = comment.userName
cell.feedCellImage.backgroundColor = UIColor.redColor()
cell.feedCellComments.text = "\(comment.replies.count) COMMENTS"
cell.repliesArray = comment.replies
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyy"
cell.feedCellDate.text = dateFormatter.stringFromDate(NSDate())
if cell.repliesArray.count > 0 {
cell.repliesTableView.rowHeight = UITableViewAutomaticDimension
}
cell.repliesTableView.reloadData()
return cell
}
How to show the inner tableview only in cells which have comments (and hiding the tableview in cells with 0 comments)?
Call super in layoutSubviews and let us know what happens.
override func layoutSubviews() {
super.layoutSubviews()
cardSetup()
}

Troubleshooting Custom UITableView Cell [Swift]

I have created a custom UITableView cell in my Storyboard that looks like this:
I hooked it up to my UITableViewCell class like this:
import UIKit
class StatusCell: UITableViewCell {
#IBOutlet weak var InstrumentImage: UIImageView!
#IBOutlet weak var InstrumentType: UILabel!
#IBOutlet weak var InstrumentValue: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Finally I attempted to initialize the UITableView from my UIViewController as such:
import UIKit
class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var TableView: UITableView!
let Items = ["Altitude","Distance","Groundspeed"]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.Items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: StatusCell! = tableView.dequeueReusableCellWithIdentifier("Cell") as StatusCell!
cell.InstrumentType?.text = Items[indexPath.row]
cell.InstrumentValue?.text = "150 Km"
cell.InstrumentImage?.image = UIImage(named: Items[indexPath.row])
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
However, when I attempt to run the program I get an EXC_BAD_INSTRUCTION error:
What could I have done wrong? Any help would be appreciated!
The debugger output shows that cell is nil, meaning it could not be instantiated. Furthermore, you are forcing an unwrapping of the optional (using the !) which causes the app to crash on the nil value.
Try to change your cellForRowAtIndexPath method like so (notice the dequeueReusableCellWithIdentifier method):
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as StatusCell
cell.InstrumentType.text = Items[indexPath.row]
cell.InstrumentValue.text = "150 Km"
cell.InstrumentImage.image = UIImage(named: Items[indexPath.row])
return cell
}
Assuming that your custom tableViewCell class is correctly set up and the outlets are bound, there is no need to check for optionals.
Place a breakpoint on the let cell = ... line and step through the code. Check if cell gets initialized and is not nil.
And please: Do not use upper case names for properties and variables (your outlets, Items array...) as upper case names are for classes, structs, ...

Resources