I have been working on making an iOS app which requires a screen/view that is scrollable and has an image, then a list and then an image and then another image (attached is the screenshot from the Android version I made)
Top of the view
View Scrolled
I have tried using the following code, which gives me the correct amount of cells but they are all blank.
//
// ServicesTableViewController.swift
// Contact Australis
//
// Created by Raghav Khanna on 22/4/18.
// Copyright © 2018 Australis. All rights reserved.
//
import UIKit
class ServiceViewCell: UITableViewCell {
#IBOutlet weak var IMage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
IMage.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
class ServiceViewCellList: UITableViewCell {
#IBOutlet weak var somethin_label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let color = UIColor(red: 0/255, green: 105/255, blue: 191/255, alpha: 1.0).cgColor
let back_colour = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0).cgColor
let back_colour_ui = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0)
let radius: CGFloat = 5
let border_width:CGFloat = 1.5
somethin_label.layer.borderColor = color
somethin_label.layer.borderWidth = border_width
somethin_label.layer.cornerRadius = radius
somethin_label.backgroundColor = back_colour_ui
}
var items_maintenance = ["Painting","All Lighting & Globe Replacemt",
"Carpet & Hard Floor Replacement","Electrical Work & Maintenance","Plumbing Work & Maintenance","Test & Tag Completion","Office Furniture Removal", "Hard Waste Removal", "Window Frosting", "All Other Handy Man & Maintenance Tasks"]
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
} class ServiceViewCellCleaning: UITableViewCell {
#IBOutlet weak var Title: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
Title.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
class ServiceViewCellCleaningList: UITableViewCell {
#IBOutlet weak var other_label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let color = UIColor(red: 0/255, green: 105/255, blue: 191/255, alpha: 1.0).cgColor
let back_colour = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0).cgColor
let back_colour_ui = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0)
let radius: CGFloat = 5
let border_width:CGFloat = 1.5
other_label.layer.borderColor = color
other_label.layer.borderWidth = border_width
other_label.layer.cornerRadius = radius
other_label.backgroundColor = back_colour_ui
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
class ServicesTableViewController: UITableViewController {
let basicCellIdentifier = "BasicCell"
var items_maintenance = ["Painting","All Lighting & Globe Replacement", "Carpet & Hard Floor Replacement","Electrical Work & Maintenance","Plumbing Work & Maintenance","Test & Tag Completion","Office Furniture Removal", "Hard Waste Removal", "Window Frosting", "All Other Handy Man & Maintenance Tasks"]
var items_cleaning = ["All Genral Comercial Cleaning","Office Cleaning", "Initial Clean","Spring Clean","Steam Carpet Cleaning","Window Washing","High Pressure Washing", "Waste Removal", "Strip & Seal Hard Floors", "Scrubbing & Buffing Hard Floors"]
let cellSpacingHeight: CGFloat = 5
#IBOutlet var table: UITableView!
func configureTableView() {
//tableView.rowHeight = UITableViewAutomaticDimension
//tableView.estimatedRowHeight = 1000.0
//let rect = CGRect(origin: .zero, size: CGSize(width: 400, height: 400))
//self.tableView = UITableView(frame: rect, style: UITableViewStyle.plain)
table.register(ServiceViewCell.self, forCellReuseIdentifier: "maintenance")
table.register(ServiceViewCellList.self, forCellReuseIdentifier: "customcell")
table.register(ServiceViewCellCleaning.self, forCellReuseIdentifier: "cleaning")
table.register(ServiceViewCellCleaningList.self, forCellReuseIdentifier: "cleaning_customcell")
}
/*func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return
}*/
override func viewDidLoad() {
super.viewDidLoad()
self.configureTableView()
table.reloadData()
table.delegate = self
table.dataSource = self
// 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.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 4
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else if section == 1 {
return items_maintenance.count
} else if section == 2 {
return 1
}
else {
return items_cleaning.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let maintenance_title = table.dequeueReusableCell(withIdentifier: "maintenance", for: indexPath) as! ServiceViewCell
let maintenance_list = table.dequeueReusableCell(withIdentifier: "customcell", for: indexPath) as! ServiceViewCellList
let cleaning_title = table.dequeueReusableCell(withIdentifier: "cleaning", for: indexPath) as! ServiceViewCellCleaning
let cleaning_list = table.dequeueReusableCell(withIdentifier: "cleaning_customcell", for: indexPath) as! ServiceViewCellCleaningList
maintenance_list.somethin_label?.text = self.items_maintenance[indexPath.row]
maintenance_list.somethin_label?.adjustsFontSizeToFitWidth = false
maintenance_list.somethin_label?.font = UIFont.systemFont(ofSize: 10.0)
cleaning_list.other_label?.text = "test"
cleaning_list.other_label?.adjustsFontSizeToFitWidth = false
cleaning_list.other_label?.font = UIFont.systemFont(ofSize: 10.0)
cleaning_title.Title?.image = UIImage(named: "cleaning.png")
maintenance_title.IMage?.image = UIImage(named: "maintenance.png")
if indexPath.section == 0 {
return maintenance_title
} else if indexPath.section == 1 {
return maintenance_list
} else if indexPath.section == 2 {
return cleaning_title
}
else {
return cleaning_list
}
return cleaning_list
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
//Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return false
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
My Storyboard looks like this (Its another view in the main storyboard with for prototype cells with custom classes) and I am struggling to figure out why I keep getting either "Unexpectedly found nil while unwrapping an Optional value" for "maintenance_list.somethin_label!.text = self.items_maintenance[indexPath.row]" or this (blank cells) when I use '?' instead of '!'.
I know why I don't get the nil while unwrapping error when using the '?'. But the real problem is why I am not being able to interact with the views in each of the cells to display the desired data. I have checked all the outlets, and they are all correct.
Any help would be greatly appreciated.
Thanks in advance.
Without having access to the entire project is difficult to say why it's not working.
But I think the approach you are following is not correct, you should look into having only two sections (Maintenance, Cleaning) and then each item of Maintenance and Cleaning would be a cell, so your datasource should return 2 sections and 10 rows for each section.
You would need a section header, which would have an image view, and then only one prototype cell, that you can reuse for any row.
Hope this helps.
Related
I have this code:
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell!.contentView.backgroundColor = .blue
cell?.textLabel?.textColor = UIColor.white
var cell2 = tableView.cellForRow(at: indexPath) as! DataTableViewCell
cell2.textLabel.textColor = UIColor.white
}
The background change works fine, but the text color change does not work.
Does anyone know why and how to fix this problem?
I think instead of writing these two lines:
cell!.textLabel?.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
cell?.textLabel?.textColor = UIColor.white
writing only a single line as:
cell.textLabel?.highlightedTextColor = .black
will work fine for you!
Use this function in your DataTableViewCell
func setHighlighted(_ highlighted: Bool,
animated: Bool)
See Apple Developer Documentation
Try any one of these:
// set highlighted color in `tableView cellForRowAt indexPath`
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell?.textLabel?.highlightedTextColor = UIColor.white
}
or try this
class CustomCell: UITableViewCell {
// As an alternate of `tableView cellForRowAt indexPath`, label text highlighted color can be set in both these methods of cell - `awakeFromNib` and `prepareForReuse`
override func awakeFromNib() {
super.awakeFromNib()
self.textLabel?.highlightedTextColor = UIColor.white
}
override func prepareForReuse() {
super.prepareForReuse()
self.textLabel?.highlightedTextColor = UIColor.white
}
// or textColor can be directly set here
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
self.textLabel?.textColor = UIColor.white
}
}
The tableView(_:didHighlightRowAt:) function is part of the Controller domain of your app while setting colors is part of the View domain (as per Model—View—Controller pattern). To keep up a good separation of responsibilities you might want to consider changing colors outside of the controller, i. e. in the cell itself. For this to work, you would create a simple UITableViewCell subclass, like so:
class MyCell: UITableViewCell {
class var reuseIdentifier: String { return "MyCell" }
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
textLabel?.textColor = UIColor.white
} else {
textLabel?.textColor = UIColor.black
}
}
}
This way the cell itself (instead of the controller) handles its own graphical representation which is the recommended way.
cell.textLabel.highlightedTextColor = [UIColor greencolor];
OK, this code works:
override func awakeFromNib () {
super.awakeFromNib ()
// Initialization code
self.titleCell? .xtxtColor = UIColor.black
self.titleCell? .highlightedTextColor = UIColor.white
}
override func setSelected (_ selected: Bool, animated: Bool) {
super.setSelected (selected, animated: animated)
// Configure the view for the selected state
}
override func prepareForReuse () {
super.prepareForReuse ()
self.titleCell? .highlightedTextColor = UIColor.white
}
Thank you very much for your help :)
I have a custom UITableView with infinite Scroll and Paging Enable. Each of my cells has UIImageView on background, I want each time I scroll up or down it will display each image as full screen.
I used this function for full screen, but my view is not full screen after one time infinite scroll.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.view.frame.size.height
}
Late Answer, Might help to others.
For Full-screen Paging of your TableViewcell. Follow the below steps.
(Consider as Without navigation bar)
TableView constrain should be with superview (not safeArea) in allside with 0 constant.
configure your Tableview like below.
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
}
private func configureTableView() {
tableView.rowHeight = UIScreen.main.bounds.height
tableView.estimatedRowHeight = UIScreen.main.bounds.height
tableView.separatorStyle = .none
tableView.isPagingEnabled = true
tableView.bounces = false
tableView.estimatedSectionHeaderHeight = CGFloat.leastNormalMagnitude
tableView.sectionHeaderHeight = CGFloat.leastNormalMagnitude
tableView.estimatedSectionFooterHeight = CGFloat.leastNormalMagnitude
tableView.sectionFooterHeight = CGFloat.leastNormalMagnitude
tableView.contentInsetAdjustmentBehavior = .never
tableView.delegate = self
tableView.dataSource = self
}
Please find below source code in which you will get table view scrolling along with the different images.
Swift 4
//
// ImageTVC.swift
//
// Created by Test User on 06/02/18.
// Copyright © 2018. All rights reserved.
//
import UIKit
class ImageTVC: UITableViewCell {
#IBOutlet weak var imgView: 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
}
}
//
// TableViewVC.swift
//
// Created by Test User on 06/02/18.
// Copyright © 2018. All rights reserved.
//
class TableViewVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension TableViewVC: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
//----------------------------------------------------------------
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell") as! ImageTVC
if indexPath.item % 2 == 0 {
cell.imgView?.backgroundColor = UIColor(red: CGFloat(indexPath.item * 2)/255.0, green: CGFloat(indexPath.item * 0)/255.0, blue: CGFloat(indexPath.item * 0)/255.0, alpha: 1.0)
} else if indexPath.item % 3 == 0 {
cell.imgView?.backgroundColor = UIColor(red: CGFloat(indexPath.item * 0)/255.0, green: CGFloat(indexPath.item * 2)/255.0, blue: CGFloat(indexPath.item * 0)/255.0, alpha: 1.0)
} else {
cell.imgView?.backgroundColor = UIColor(red: CGFloat(indexPath.item * 0)/255.0, green: CGFloat(indexPath.item * 0)/255.0, blue: CGFloat(indexPath.item * 2)/255.0, alpha: 1.0)
}
print("IndexPath.row = \(indexPath.row)")
return cell
}
//----------------------------------------------------------------
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return tableView.bounds.size.height
}
}
Also find storyboard design.
I am working on a 'UITableView' with different section headers. Section header contains a tab gesture recognization to expand and collapse the section.
In the section header view, I have used an image for the accessory icon to show the user the section is expanded or collapsed.
My concern is when I tap section header then control goes to the gesture method. In that method how should I get the header cell to update the image accordingly?
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
if self.useSearchDefinitions {
if let ret = tableView.dequeueReusableCell(withIdentifier: INBOX_HEADER_CELL_IDENTIFIER) as? InboxHeaderCell {
ret.contentView.backgroundColor = UIColor(red: 236 / 255.0, green: 236 / 255.0, blue: 236 / 255.0, alpha: 1.0)
ret.contentView.tag = section
ret.lblHeaderTitle?.textColor = UIColor(red: 110 / 255.0, green: 110 / 255.0, blue: 110 / 255.0, alpha: 1.0)
ret.lblHeaderTitle?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
ret.lblHeaderTitle?.text = presenter.sectionTitle(section)
ret.accessoryImage.image = UIImage(named: "inbox-expand.png")
// Set tap gesture
let headerViewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.headerViewGestureHandler))
headerViewTapRecognizer.delegate = self
headerViewTapRecognizer.numberOfTouchesRequired = 1
headerViewTapRecognizer.numberOfTapsRequired = 1
ret.contentView.addGestureRecognizer(headerViewTapRecognizer)
return ret.contentView
}
}
return nil
}
and this is to get the gesture
func headerViewGestureHandler(_ sender: UIGestureRecognizer)
{
tableView.beginUpdates()
if let tag = sender.view?.tag {
let section = Int(tag)
let shouldCollapse: Bool = !collapsedSections.contains((section))
let numOfRows = Int(presenter.numberOfRows(tag))
}
}
how should I get the particular clicked section header cell in this method so I can update the image accordingly?
Thanks in advance.
I would recommend:
put the Gesture code inside your section header
using a "call back" closure for passing the tap back to the view controller
Here is a simple example (assumes you have a View Controller with a Table View, hooked up via IBOutlet):
class SimpleSectionHeaderView: UITableViewHeaderFooterView, UIGestureRecognizerDelegate {
// typical UILabel
var lblHeaderTitle: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
// this is our "call back" closure
var headerTapCallback: (() -> ())?
func headerViewGestureHandler(_ sender: UIGestureRecognizer) {
// just for debugging, so we know the tap was triggered
print("tapped!!!")
// "call back" to the view controller
headerTapCallback?()
}
func commonInit() {
// set our backgroundColor
contentView.backgroundColor = .cyan
// add a label and set its constraints
self.addSubview(lblHeaderTitle)
lblHeaderTitle.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8.0).isActive = true
lblHeaderTitle.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0.0).isActive = true
// Set tap gesture
let headerViewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.headerViewGestureHandler))
headerViewTapRecognizer.delegate = self
headerViewTapRecognizer.numberOfTouchesRequired = 1
headerViewTapRecognizer.numberOfTapsRequired = 1
// add it to self
self.addGestureRecognizer(headerViewTapRecognizer)
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
}
class TableWithSectionHeadersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var theTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// standard cell registration
theTableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
theTableView.register(SimpleSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: "simpleHeaderView")
// make sure these are set (in case we forgot in storyboard)
theTableView.delegate = self
theTableView.dataSource = self
}
func handleHeaderTap(_ section: Int) -> Void {
// do whatever we want based on which section header was tapped
print("View Controller received a \"tapped\" in header for section:", section)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let v = tableView.dequeueReusableHeaderFooterView(withIdentifier: "simpleHeaderView") as! SimpleSectionHeaderView
// set the view's label text
v.lblHeaderTitle.text = "Section \(section)"
// set the view's "call back" closure
v.headerTapCallback = {
_ in
self.handleHeaderTap(section)
}
return v
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60;
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
cell.textLabel?.text = "\(indexPath)"
return cell
}
}
This also eliminates any need to set any .tag properties (which is generally a bad idea, for a number of reasons).
Anytime I tap segmented control in UICell, immediately some other cell gets this segmented control in the same position. It looks like segmented control recognizes that not only this particular one was tapped but also some other one in other cell.
Have you ever encountered issue like this?
this is my custom cell implementation:
class QuestionYesNoCustomCellTableViewCell: UITableViewCell {
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var segmentControl: ADVSegmentedControl!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
segmentControl.items = ["TAK", "NIE"]
segmentControl.font = UIFont(name: "Avenir-Black", size: 12)
segmentControl.borderColor = UIColor.grayColor()
segmentControl.selectedIndex = 1
segmentControl.selectedLabelColor = UIColor.whiteColor()
segmentControl.unselectedLabelColor = UIColor.grayColor()
segmentControl.thumbColor = UIColor(red: 46.0/255.0, green: 204.0/255.0, blue: 113.0/255.0, alpha: 1.0)
segmentControl.addTarget(self, action: "segmentValueChanged:", forControlEvents: .ValueChanged)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func segmentValueChanged(sender: AnyObject?){
if segmentControl.selectedIndex == 0 {
segmentControl.thumbColor = UIColor(red: 231.0/255.0, green: 76.0/255.0, blue: 60.0/255.0, alpha: 1.0)
segmentControl.selectedLabelColor = UIColor.whiteColor()
segmentControl.unselectedLabelColor = UIColor.grayColor()
}else if segmentControl.selectedIndex == 1{
segmentControl.thumbColor = UIColor(red: 46.0/255.0, green: 204.0/255.0, blue: 113.0/255.0, alpha: 1.0)
segmentControl.selectedLabelColor = UIColor.grayColor()
segmentControl.unselectedLabelColor = UIColor.whiteColor()
}
}
Also, I think it is worth to provide my tableView delegate methods implemented
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (dict2 as NSDictionary).objectForKey(dictKeysSorted[section])!.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: QuestionYesNoCustomCellTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as! QuestionYesNoCustomCellTableViewCell
cell.questionLabel.text = (dict2 as NSDictionary).objectForKey(dictKeysSorted[indexPath.section])![indexPath.row] as? String
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor(red: 245.0/255.0, green: 245.0/255.0, blue: 245.0/255.0, alpha: 1.0)
}
else {
cell.backgroundColor = UIColor(red: 225.0/255.0, green: 225.0/255.0, blue: 225.0/255.0, alpha: 0.7)
}
return cell
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return dictKeysSorted[section]
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCellWithIdentifier("CellHeader") as! CustomHeaderCell
headerCell.backgroundColor = UIColor(red: 20.0/255.0, green: 159.0/255.0, blue: 198.0/255.0, alpha: 1.0)
headerCell.headerLabel.text = dictKeysSorted[section]
return headerCell
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 70.0
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return dictKeysSorted.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 110.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
To recap what the problem actually is: In every tableView cell there is a segment control. When I change the position of the one located in first row, I scroll down and see that segment control in row 5 also has been moved despite the fact it should be in the default position.
Thanks in advance
EDIT:
I recognized one of the biggest problem in solutions below - they are good as long as you don't use section in tableView. The thing is, from what I have discovered right now, in each sections the rows are counted over from 0.
This might be the cause when you are using reusing the cells, when you scroll the cell you changed will be shown again for another row.
To avoid this when you reuse cell make sure you reset the data in it also
In your case you have to check if the segmented value is changed then change the segmented control value also in cellForRowAtIndexPath
Please let me know if you need more explanation.
Here is a sample project for you sampleTableReuse
It's because of reusable nature of UITableViewCells. You must keep track in your datasource selected segment index for each row. Then in cellForRowAtIndexPath you must set it properly for each cell.
example
define somewhere an enum with possible Answers:
enum Answer {
case Yes
case No
case None
}
then define and init your answers' array:
var answer = [Answer](count: numberOfQuestions, repeatedValue: .None)
in your cell's implementation add a method to configure a cell with Answer
func setupWithAnswer(answer: Answer)
{
var selectedIdex = UISegmentedControlNoSegment
switch answer {
case .Yes: selectedIdex = 0
case .No: selectedIdex = 1
default: break
}
self.segmentedControl.selectedSegmentIndex = selectedIdex
}
and finally, in your cellForRowAtIndex do after dequeuing
cell.setupWithAnswer(answer: self.answers[indexPath.row])
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