UITableView.automaticDimension Not working tableView detailTextLabel - ios

I am implementing UITableViewController Programmatically (No Storyboards!).
I tried many possible ways to implement automatic resizing of TableViewCell's detailTextLabel but none is working. I don't know what I am missing or whether it's a bug! Here's what I tried:
//Class - tableViewContoller
override func viewDidLoad() {
super.viewDidLoad()
setUpTableView()
}
func setUpTableView() {
tableView.tableFooterView = UIView(frame: CGRect.zero)
tableView.separatorColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.8)
tableView.contentInset = UIEdgeInsets(top: 10.0, left: 0.0, bottom: 10.0, right: 0.0)
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = UITableView.automaticDimension //Tried 44 -> Not working either
tableView.reloadData()
}
//cellForRowAt IndexPath
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: cellId)
if cell == nil {
cell = UITableViewCell(style: UITableViewCell.CellStyle.value1, reuseIdentifier: cellId)
}
cell?.detailTextLabel?.numberOfLines = 0
cell?.detailTextLabel?.lineBreakMode = .byWordWrapping
cell?.selectionStyle = .none
switch indexPath.row {
case 0:
cell?.textLabel?.text = "Case 1"
cell?.detailTextLabel?.text = caseDetails?.details
case 1:
cell?.textLabel?.text = "Case 2"
cell?.detailTextLabel?.text = caseDetails?.bio
default:break
}
return cell!
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
I have 2-3 cells where detailTextLabel may have multiple lines.
Please let me know what's that I'm missing here. What I figured after reading on the Internet is to add custom constraints, but I don't think that'll work either.

You have to add constraints for that cell?.detailTextLabel
cellForRowAt
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: cellId)
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: cellId)
}
cell?.detailTextLabel?.numberOfLines = 0
cell?.detailTextLabel?.lineBreakMode = .byWordWrapping
cell?.selectionStyle = .none
cell?.detailTextLabel?.layer.backgroundColor = UIColor.yellow.cgColor
// ALLOW MANUAL CONSTRAINTS
cell?.detailTextLabel?.translatesAutoresizingMaskIntoConstraints = false
// TOP +15, BOTTOM -15, RIGHT -15
cell?.detailTextLabel?.topAnchor.constraint(equalTo: (cell?.contentView.topAnchor)!, constant: 15).isActive = true
cell?.detailTextLabel?.bottomAnchor.constraint(equalTo: (cell?.contentView.bottomAnchor)!, constant: -15).isActive = true
cell?.detailTextLabel?.rightAnchor.constraint(equalTo: (cell?.contentView.rightAnchor)!, constant: -10).isActive = true
switch indexPath.row {
case 0:
cell?.textLabel?.text = "Case 1"
cell?.detailTextLabel?.text = "hi\nhello\nwelcome\nhow are you"
case 1:
cell?.textLabel?.text = "Case 2"
cell?.detailTextLabel?.text = "caseDetails?.bio\n\n\n123456"
default:break
}
return cell!
}
Output

Should work if you set your estimated row height to an actual value. You can't have both set to .automaticDimension.

Related

How to add UISwitch to a specific UITableView cell programmatically

I am relatively new to UIKit. Currently, I am trying to create a UISwitch that will show up on a specific UITableView cell. However, I can't seem to figure out how to do this. Instead, I am getting a UISwitch on every single cell in the UITableView.
My code is below:
import UIKit
class SettingsVC: UIViewController {
var tableView = UITableView(frame: .zero, style: .insetGrouped)
let cells = ["Change Accent Color", "Change Currency Symbol", "Vibrations"]
let cellReuseIdentifier = "cell"
override func viewDidLoad() {
super.viewDidLoad()
createTableView()
setTableViewDelegates()
}
func createTableView() {
view.addSubview(tableView)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
tableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.leftAnchor.constraint(equalTo: view.leftAnchor),
tableView.rightAnchor.constraint(equalTo: view.rightAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
func setTableViewDelegates() {
tableView.delegate = self
tableView.dataSource = self
}
}
extension SettingsVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cells.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {
return UITableViewCell()
}
cell.textLabel?.text = cells[indexPath.row]
let switchView = UISwitch(frame: .zero)
switchView.setOn(false, animated: true)
cell.accessoryView = switchView
return cell
}
}
This is how my UITableView looks currently in the simulator.
This is how I would like the UITableView to look.
How would I be able to achieve the look I'm going for? Any help would be greatly appreciated.
The method tableView(_:cellForRowAt:) is used to create all cells for a table, so the code inside this method is called for each cell. You need to figure out a condition that distinguishes the cell with a UISwitch and run the corresponding piece conditionally. Conceptually, something like this:
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {
return UITableViewCell()
}
cell.textLabel?.text = cells[indexPath.row]
if isSwitchNeeded { // Here.
let switchView = UISwitch(frame: .zero)
switchView.setOn(false, animated: true)
cell.accessoryView = switchView
}
return cell
}
There are some architectural options that might allow you do that. One of them is to rely on the index path. For instance, this should work in your raw example:
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {
return UITableViewCell()
}
cell.textLabel?.text = cells[indexPath.row]
if indexPath.row == 2 {
let switchView = UISwitch(frame: .zero)
switchView.setOn(false, animated: true)
cell.accessoryView = switchView
}
return cell
}
And a million other ways.
First of all most likely you want to save the value of the switch, so create a property on the top level of the view controller
var enableVibrations = false
Second of all cells are reused. Even if there are only three cells it's good practice to set all UI elements to a defined state, that means to set the accessory view to nil if there is no switch.
And there is a dequeueReusableCell API which returns a non-optional cell.
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let title = cells[indexPath.row]
cell.textLabel?.text = title
if title == "Vibrations" {
let switchView = UISwitch(frame: .zero)
switchView.setOn(enableVibrations, animated: true)
switchView.addTarget(self, action: #selector(toggleVibrations), for: .valueChanged)
cell.accessoryView = switchView
} else {
cell.accessoryView = nil
}
return cell
}
And add the action method
#objc func toggleVibrations(_ sender : UISwitch) {
self.enableVibrations = sender.isOn
}

Why does my TableViewCell doesn't show other data

I intended to display data from my Firestore Database into my app using the TableViewCell. It supposed to show the bookTitle, bookAuthor and bookSummary but the bookAuthor does not show up. Below is my code.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = books[indexPath.row].bookTitle
cell.textLabel?.font = .systemFont(ofSize: 20, weight: .medium)
cell.detailTextLabel?.text = books[indexPath.row].bookAuthor
cell.detailTextLabel?.text = books[indexPath.row].bookSummary
return cell
}
func setupTableView() {
view.addSubview(tableView)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.allowsSelection = true
tableView.isUserInteractionEnabled = true
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return books.count
}
You're setting the same label to bookAuthor and bookSummary here:
cell.detailTextLabel?.text = books[indexPath.row].bookAuthor
cell.detailTextLabel?.text = books[indexPath.row].bookSummary
So, it gets set to bookAuthor, and then immediately overwritten by bookSummary.
You could create/use another label for one of the fields, or concatenate the strings for this single label:
cell.detailTextLabel?.text = "\(books[indexPath.row].bookAuthor ?? "") - \(books[indexPath.row].bookSummary ?? "")"
As You had used textLabel and detailTextLabel: It's used for giving label and a subtitle. You can't use detailTextLabel twice. So its overriding your bookAuthor by bookSummary.
Please try to write like this:-
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = books[indexPath.row].bookTitle
cell.textLabel?.font = .systemFont(ofSize: 20, weight: .medium)
cell.detailTextLabel?.text = books[indexPath.row].bookAuthor + "\n" + books[indexPath.row].bookSummary
return cell
}

AutoResizing header & Cell in Programmatically UITableView

I have UIViewTable created programmatically
I customised the headers and cell look via Extension.
All I need is to make the large amount of texts displayed in header/cell to be viewed with:
lineBreakMode = NSLineBreakMode.byWordWrapping // enable multi line
numberOfLines = 0 // for Automatic size
I nearly used everything, but nothing is working.
I used:
self.tableView.estimatedRowHeight = 200.0
self.tableView.rowHeight = UITableView.automaticDimension
I put:
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
I also did:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
Nothing seems to work
here is my Extension:
extension indexController {
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let subDatas = sections[section].sub_catigories // [1]
return subDatas?.count ?? 0
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let currentSection = sections[indexPath.section]
let currentSubdata = currentSection.sub_catigories?[indexPath.row]
//print(currentSubdata!.id)
let vc = indexControllerTwo()
vc.catNumber = currentSubdata!.id
vc.sectionTitle = currentSubdata?.name
navigationController?.pushViewController(vc, animated: true)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellid", for: indexPath)
// [2]
let currentSection = sections[indexPath.section]
let currentSubdata = currentSection.sub_catigories![indexPath.row]
// use listCell
guard let titleCell = cell as? listCell else {
return cell
}
titleCell.titleLabel.text = currentSubdata.name
titleCell.listCount.text = "\(currentSubdata.number_of_subcatigories ?? 0)"
// titleCell.titleLabel.numberOfLines = 3
// titleCell.titleLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
// titleCell.titleLabel.baselineAdjustment = .alignCenters
// titleCell.titleLabel.adjustsFontSizeToFitWidth = true
// self.tableView.estimatedRowHeight = 200.0
// self.tableView.rowHeight = UITableView.automaticDimension
cell.layer.backgroundColor = UIColor.clear.cgColor
return cell
}
Please note that: listCell is just for customization and constraint
and here it is:
import UIKit
class listCell: UITableViewCell {
var safeArea: UILayoutGuide!
let imageCell = UIImageView()
let titleLabel = UILabel()
let subTitleLabel = UILabel()
let listCount = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView(){
safeArea = layoutMarginsGuide
setupTitleLabel()
setupListCount()
}
func setupTitleLabel(){
addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleLabel.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor),
titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: 7)
])
titleLabel.font = UIFont(name: "verdana-Bold", size: 16)
}
func setupListCount(){
addSubview(listCount)
listCount.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
listCount.leadingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -30),
listCount.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: -11)
])
listCount.font = UIFont(name: "verdana", size: 10)
}
}
Please help me make the header and cell text field to be auto resizing.
thanks for your time.

Swift- Assigning arrays to tableview within collectionviewcell

I'm learning Swift while building an app. Anyways, I'm trying to assign 4 different arrays into 4 different tableview within 4 different collectionviewcells. I was wondering how I will be able to put:
var fallQuarter : [String] = ["HELLO", "HELLO"]
var winterQuarter : [String] = ["BYE", "BYE", "BYE"]
var springQuarter : [String] = ["HI", "HI"]
var summerQuarter : [String] = ["OKAY", "OKAY"]
these four arrays (for example) to the tableview within collectionviewcell.
Right now, each of the tableview in each collectionviewcell seems to display all 9 items of these 4 arrays. However, I want to assign each array to each tableview within the collectionviewcell. Thanks for your help in advance .
Here is the main code:
import UIKit
class yearOne: UICollectionViewController {
let customCellIdentifier = "cellID"
let quarters = [
customLabel (title: "Fall Quarter"),
customLabel (title: "Winter Quarter"),
customLabel (title: "Spring Quarter"),
customLabel (title: "Summer Quarter")
]
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.register(quarterCell.self, forCellWithReuseIdentifier:
customCellIdentifier)
navigationItem.title = "Year One"
navigationController?.navigationBar.prefersLargeTitles = true
collectionView?.backgroundColor = .lightGray
//navigationItem.prompt = "Click the + button to add courses, Swipe left on a course
to delete."
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection
section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return quarters.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt
indexPath:IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier:
customCellIdentifier,
for: indexPath) as! quarterCell
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 5
cell.quarters = self.quarters[indexPath.row]
return cell
}
#objc func buttonAction(sender: UIButton!) {
let destination = SearchPage()
navigationController?.pushViewController(destination, animated: true)
}
}
Here is the extension:
extension yearOne : UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (view.frame.width - 30)
return CGSize(width: width, height: 200)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
UIEdgeInsets(top: 30, left: 10, bottom: 30, right: 10)
}
}
Here is the quarterCell:
class quarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource{
var fallQuarter : [String] = ["HELLO", "HELLO"]
var winterQuarter : [String] = ["BYE", "BYE", "BYE"]
var springQuarter : [String] = ["HI", "HI"]
var summerQuarter : [String] = ["OKAY", "OKAY"]
let tableView:UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
return tableView
}()
let cellId = "coursesName"
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return fallQuarter.count
case 1:
return winterQuarter.count
case 2:
return springQuarter.count
case 3:
return summerQuarter.count
default:
return 5
}
}
let sectionsArray: [String] = ["fall", "winter", "spring", "summer"]
func numberOfSections(in tableView: UITableView) -> Int {
return sectionsArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
let sectionName = sectionsArray[indexPath.section]
tableView.backgroundColor = UIColor.white
switch sectionName {
case "fall":
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let fall = self.fallQuarter[indexPath.row]
cell.textLabel?.text = fall
cell.backgroundColor = UIColor.white
return cell
case "winter":
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let winter = self.winterQuarter[indexPath.row]
cell.textLabel?.text = winter
cell.backgroundColor = UIColor.white
return cell
case "spring":
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let spring = self.springQuarter[indexPath.row]
cell.textLabel?.text = spring
cell.backgroundColor = UIColor.white
return cell
case "summer":
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let summer = self.summerQuarter[indexPath.row]
cell.textLabel?.text = summer
cell.backgroundColor = UIColor.white
return cell
default:
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 40
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle:
UITableViewCell.EditingStyle,forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
// handle delete (by removing the data from your array and updating the
tableview)
self.tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//add class information???
}
var quarters: customLabel? {
didSet {
guard let quarters = quarters else {return}
quarterLabel.text = quarters.title
}
}
override init(frame: CGRect){
super.init(frame: frame)
addSubview(tableView)
setupView()
}
func setupView(){
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
self.backgroundColor = UIColor.white
contentView.addSubview(quarterLabel)
contentView.addSubview(addButton)
quarterLabel.translatesAutoresizingMaskIntoConstraints = false
quarterLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant:
10).isActive = true
quarterLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant:
10).isActive = true
addButton.translatesAutoresizingMaskIntoConstraints = false
addButton.topAnchor.constraint(equalTo: quarterLabel.topAnchor, constant:
-5).isActive = true
addButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant:
-10).isActive = true
addButton.heightAnchor.constraint(equalToConstant: 25).isActive = true
addButton.widthAnchor.constraint(equalToConstant: 25).isActive = true
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: contentView.topAnchor, constant:
35).isActive = true
tableView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant:
5).isActive = true
tableView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant:
-10).isActive = true
tableView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant:
-5).isActive = true
// each collection view cell (row) = should display xxQuarter Array
// call indexpath for the collection view and set the tableview to the collection
view
// quarterCell.indexPath
//if(buttonAction) is cicked from searchPage(), then add the UI label
//remove course function, add course function
}
let quarterLabel : UILabel = {
let label = UILabel()//frame: CGRect(x: 15, y: -75, width: 300, height: 50))
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor.black
label.font = UIFont.boldSystemFont(ofSize: 16)
//label.textAlignment = .center
return label
}()
let addButton : UIButton = {
let button = UIButton()//frame: CGRect(x: 345, y: 10, width: 30, height: 30))
button.setImage(UIImage(named: "addicon"), for: .normal)
button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
button.addTarget(self, action: #selector(yearOne.buttonAction), for: .touchUpInside)
return button
}()
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Maybe you can try with multidimensional array:
let data = [["HELLO", "HELLO"], ["BYE", "BYE", "BYE"], ["HI", "HI"], ["OKAY", "OKAY"]]
For the number of sections use:
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return data.count
}
Then, to specify the number of rows in each section use:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data[section].count
}
Then setup your cells:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
cell.textLabel?.text = data[indexPath.section][indexPath.row]
}
I was able to figure out a solution for anyone in the future to see...
I made four different customCellIdentifier and registered for four different collectionViewCell
class yearOne: UICollectionViewController {
let customCellIdentifier = "cellID"
let customCellIdentifier2 = "cellID2"
let customCellIdentifier3 = "cellID3"
let customCellIdentifier4 = "cellID4"
let quarters = [
customLabel (title: "Fall Quarter"),
customLabel (title: "Winter Quarter"),
customLabel (title: "Spring Quarter"),
customLabel (title: "Summer Quarter")
]
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.register(fallQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier)//
self.collectionView!.register(winterQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier2)
self.collectionView!.register(springQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier3)
self.collectionView!.register(summerQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier4)
navigationItem.title = "Year One"
navigationController?.navigationBar.prefersLargeTitles = true
collectionView?.backgroundColor = .lightGray
//navigationItem.prompt = "Click the + button to add courses, Swipe left on a course to delete."
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return quarters.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if (indexPath.row == 0){
let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as! fallQuarterCell
cell1.layer.borderColor = UIColor.red.cgColor
cell1.layer.borderWidth = 2
cell1.layer.cornerRadius = 5
cell1.quarters = self.quarters[0]
return cell1
}
else if (indexPath.row == 1){
let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier2, for: indexPath) as! winterQuarterCell
cell2.layer.borderColor = UIColor.yellow.cgColor
cell2.layer.borderWidth = 1
cell2.layer.cornerRadius = 5
cell2.quarters = self.quarters[1]
return cell2
}
else if (indexPath.row == 2){
let cell3 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier3, for: indexPath) as! springQuarterCell
cell3.layer.borderColor = UIColor.green.cgColor
cell3.layer.borderWidth = 1
cell3.layer.cornerRadius = 5
cell3.quarters = self.quarters[2]
return cell3
}
else if (indexPath.row == 3){
let cell4 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier4, for: indexPath) as! summerQuarterCell
cell4.layer.borderColor = UIColor.blue.cgColor
cell4.layer.borderWidth = 1
cell4.layer.cornerRadius = 5
cell4.quarters = self.quarters[3]
return cell4
}
else{
return UICollectionViewCell()
}
}
Then I made four different class and created a different array of data in each
class fallQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource
class winterQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource
class springQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource
class summerQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource
Thanks everyone for the help!

UITableView keeps autoscrolling to top

When the user tries scrolling down the table (goes past the keyboard height), it automatically scrolls back to the top of table, leaving the user unable to press any of the keys in the bottoms rows of the table. How do I disable this autoscroll to top? Note this is different from the scrollsToTop property.
import UIKit
class KeyboardViewController: UIInputViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView = UITableView()
let screenSize: CGRect = UIScreen.mainScreen().bounds
let buttonTitles = [
"XX",
"YY"
]
override func viewDidLoad() {
super.viewDidLoad()
let screenWidth = screenSize.width
let screenHeight = screenSize.height
tableView.frame = CGRectMake(0,0,screenWidth,screenHeight - 40)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self,forCellReuseIdentifier: "cell")
self.view.addSubview(tableView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.buttonTitles.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = self.buttonTitles[indexPath.row]
cell.textLabel?.textAlignment = .Center
cell.textLabel?.font = UIFont(name: "Helvetica Neue", size: 14)
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.numberOfLines = 0
cell.backgroundColor = UIColor(red: 176/255, green: 15/255, blue: 15/255, alpha: 1.0)
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = UIEdgeInsetsZero
cell.separatorInset = UIEdgeInsetsZero
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var string = buttonTitles[indexPath.row]
(textDocumentProxy as! UIKeyInput).insertText("\(string)")
}
Move your code except
tableView.delegate = self
tableView.dataSource = self
to viewWillAppear

Resources