Swift: Change height of UINavigationController view - swift

I have a UITableView embedded in a UINavigationController. The UITableView is set up as follows:
import UIKit
class HistoryTableViewController: UITableViewController {
let cellID = "HistoryColumns"
struct CellData {
let date: String?
let number: String?
let before: String?
let after: String?
let diff: String?
let strength: String?
let location: String?
}
var data = [CellData]()
override func viewDidLoad() {
super.viewDidLoad()
data = [
// data goes here
]
tableView.register(HistoryTableViewCell.self, forCellReuseIdentifier: cellID)
self.navigationController?.navigationBar.topItem?.title = "Recent Activity"
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID) as! HistoryTableViewCell
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor.orange.withAlphaComponent(0.3)
}
cell.date.valueLabel.text = data[indexPath.row].date
cell.number.valueLabel.text = data[indexPath.row].flightNumber
cell.before.valueLabel.text = data[indexPath.row].preFuel
cell.after.valueLabel.text = data[indexPath.row].postFuel
cell.diff.valueLabel.text = data[indexPath.row].uplift
cell.strength.valueLabel.text = data[indexPath.row].density
cell.location.valueLabel.text = data[indexPath.row].location
return cell
}
}
I call the controller within a UINavigationController as follows:
#objc func handleTap(_ sender: UITapGestureRecognizer? = nil) {
DispatchQueue.asyncMain {
let history = HistoryTableViewController()
let navigationController = UINavigationController(rootViewController: history)
self.present(navigationController, animated: true, completion: nil)
}
}
What I want to do is to define the height of the navigationController's view here (around 500). I've tried using navigationController.view.heightAnchor.constraint but it had no effect (obviously I set translatesAutoresizingMaskIntoConstraints to false first)...
I do want to use a UINavigationController here because I need the navbar that comes with it. Any suggestions greatly appreciated...

When you say .present, the way the presented view controller occupies the screen is up to you. Make a custom transition and supply your own UIPresentationController subclass with an implementation of frameOfPresentedViewInContainerView to say where the presented view controller's view should go.
This is a silly example with a custom animation as well, but you don't have to customize the animation if you don't want to. The important thing is that I've made the presented view controller smaller than it normally would be.

Related

Swift - Delegate function not returning value

VC-A is embedded in a nav controller and has a button going to VC-B via a popover segue. VC-B has a table view with a few font names. When I select a font name, VC-B closes and, using delegate/protocol, VC-A should get the selected name. It does not. I found that if I set a breakpoint at the end of didSelectRowAt, delegate is nil for some reason.
VC-A
class ViewController: UIViewController, FontDelegate {
#IBOutlet weak var infoLabel: UILabel!
let fontTable = FontTableTableViewController()
override func viewDidLoad() {
super.viewDidLoad()
fontTable.delegate = self
}
func getFontName(data: String) {
infoLabel.text = data
}
}
VC-B
protocol FontDelegate {
func getFontName(data: String)
}
class FontTableTableViewController: UITableViewController {
let fontArray = ["Helvetica", "Arial", "Monaco"]
var delegate: FontDelegate?
// MARK: - Table view functions go here...
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let font = fontArray[indexPath.row]
self.delegate?.getFontName(data: font)
self.dismiss(animated: true, completion: nil)
}
}
This shows the storyboard connection from the button in VC-A to VC-B.
Instead of linking Pick your font button to the other controller, I would suggest you creating an IBAction of the button to trigger the following code whenever pressed:
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
guard let vc = storyBoard.instantiateViewController(withIdentifier: "FontScreen") as? FontTableTableViewController else {return}
vc.delegate = self
vc.modalPresentationStyle = .fullScreen
self.navigationController?.pushViewController(vc, animated: true)
but for this to work you will need to go to the identity inspector of your FontTableTableViewController and from there you can name your controller in storyboardID field in Identity section as FontScreen.
This is not the way how to return a variable in a navigation controller Environment. I would like to suggest you use an unwind segue. Your code would then look like:
VC A
class ViewController: UIViewController {
var selectedFontName = ""
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func returnSelectedFont(sender: UIStoryboardSegue) {
print(selectedFontName)
}
}
The IBAction in VC A ist the method too which the tableview returns to if you use an unwind segue.
Your tableview controller then looks like this:
VC B
import UIKit
class FontTableTableViewController: UITableViewController {
var selectedFont = ""
let fontArray = ["Helvetica", "Arial", "Monaco"]
#IBOutlet var fontTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
fontTable.dataSource = self
fontTable.delegate = self
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return fontArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FontTable", for: indexPath) as! FontCell
cell.fontName.text = fontArray[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedFont = fontArray[indexPath.row]
performSegue(withIdentifier: "Return Fontname", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let returnVC = segue.destination as? ViewController {
returnVC.selectedFontName = selectedFont
}
}
}
To be able to get the return segue working you have to select the tableview cell and control drag it to the exit icon in the tableview controller. See therefore the picture.
After that you select the unwind segue and give it an identifier, to be used in VC B. See the code:
This should work perfectly.

CellForRowAtIndexPath not Called when reloading table data

I've worked through a lot of answers like this one but I'm still stuck.
I have a viewcontroller with a collectionView and a searchController. When the user searches I want to display a UITableView on top of the collectionView. I'm trying to add the tableview programmatically b/c it's a simple text label I'm displaying
I am able to display the search results for the dummy array I have in viewdidload of my tableviewcontroller class. However when I get the actual results, I can only print them in the numberOfRows function.
All help would be greatly appreciated, here's my code:
This is my TableView Class:
import UIKit
class HashtagSearchList: UITableViewController {
var hashtagListTableview = UITableView()
var hashtagList = [String]()
override func viewDidLoad() {
super.viewDidLoad()
hashtagList = ["One", "Two", "Three"]
hashtagListTableview.delegate = self
hashtagListTableview.dataSource = self
}
// MARK: - Table view data source
//I don't need this, but added it based on some answers... didn't help
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//All these print statements show correct values
print("List Count = \(hashtagList.count)")
print("List of Strings: \(hashtagList)")
print("frame size = \(tableView.frame)")
return hashtagList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
//This print statement only fires on ViewdidLoad
print("cellForRowAt = \(hashtagList[indexPath.row])")
cell.textLabel?.text = hashtagList[indexPath.row]
cell.backgroundColor = .red
return cell
}
}
Here is my ViewController / SearchController code:
class ExploreVC: UIViewController {
var hashtagSearchController = HashtagSearchList()
override func viewDidLoad() {
super.viewDidLoad()
//Search Controller
navigationItem.searchController = searchController
searchController = UISearchController(searchResultsController: hashtagSearchController)
}
//......
// SEARCH CONTROLLER
extension ExploreVC: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
let searchText = searchController.searchBar.text
if searchText == "" { return }
PostFirebase.getHashtagList(hashtag: searchText) { (hashtagList) in
self.hashtagSearchController.hashtagListTableview.frame = CGRect(x: 0.0, y: 0.0, width: self.view.bounds.width, height: self.view.bounds.height)
self.hashtagSearchController.hashtagList = hashtagList
//self.hashtagSearchController.hashtagListTableview.reloadData()
DispatchQueue.main.async {
self.hashtagSearchController.hashtagListTableview.reloadData()
}
}
}
}
}
Here is the tableview from viewDidLoad, and it never changes from here
You initialized hashtagListTableview in HashtagSearchList but you didn't add layout constraints. By default, it will have .zero frame and won't be displayed on the screen.
I guess that the table view on the screen is tableView from UITableViewController. That's why nothing happened when you call self.hashtagSearchController.hashtagListTableview.reloadData().
To fix it, try to use tableView instead of hashtagListTableview. Replace
self.hashtagSearchController.hashtagListTableview.reloadData()
with
self.hashtagSearchController.tableView.reloadData()

Can't get indexPath of cell in header

I have created prototype custom header cell for a tableView with a button on it. I am trying to get the indexPath of the cell when the button is tapped, but I don't receive it. Any idea what I am doing wrong here?
protocol MediaHeaderCellDelegate: class {
func editPost(cell: MediaHeaderCell)
}
class MediaHeaderCell: UITableViewCell {
weak var delegate: MediaHeaderCellDelegate?
#IBAction func moreOptionsAction(_ sender: UIButton) {
delegate?.editPost(cell: self)
}
}
class NewsfeedTableViewController:UITableViewController, MediaHeaderCellDelegate {
func editPost(cell: MediaHeaderCell) {
guard let indexPath = tableView.indexPath(for: cell) else {
print("indexpath could not be given")
return}
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.mediaHeaderCell) as! MediaHeaderCell
cell.delegate = self
cell.media = media[section]
return cell
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.mediaCell, for: indexPath) as! MediaTableViewCell
cell.currentUser = currentUser
cell.media = media[indexPath.section]
cell.delegate = self
return cell
}
}
So this is actually all about learning what section a section header belongs to?? Here’s what I do. I have a header class:
class MyHeaderView : UITableViewHeaderFooterView {
var section = 0
}
I register it:
self.tableView.register(
MyHeaderView.self, forHeaderFooterViewReuseIdentifier: self.headerID)
I use and configure it:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let h = tableView
.dequeueReusableHeaderFooterView(withIdentifier: self.headerID) as! MyHeaderView
// other stuff
h.section = section // *
return h
}
Now if the header view is tappable or contains a button or whatever, learning what section this is the header of is trivial.
Your immediate issue is that you are using a table cell as a section header view. That should not be done. Once you resolve that, your next task is to determine the table section from the header view whose button was tapped.
First, change your MediaHeaderCell to be a header view that extends UITableViewHeaderFooterView and update your protocol accordingly:
protocol MediaHeaderViewDelegate: class {
func editPost(view: MediaHeaderView)
}
class MediaHeaderView: UITableViewHeaderFooterView {
weak var delegate: MediaHeaderViewDelegate?
#IBAction func moreOptionsAction(_ sender: UIButton) {
delegate?.editPost(cell: self)
}
}
Then you need to register the header view in your view controller.
Then update your viewForHeaderInSection:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: Storyboard.mediaHeaderView) as! MediaHeaderView
view.delegate = self
view.media = media[section]
view.tag = section
return view
}
And last, update your protocol method implementation:
func editPost(view: MediaHeaderView) {
let section = view.tag
// do something
}
There is one possible issue with this. If your table allows sections to be added or removed, then it is possible that a header view's tag could be wrong when the button is tapped.

How to use navigationController to show up a WebView when I choose one cell from the tableView?

When we choose one cell from the tableView, we use the didSelectRowAtIndexPath method to implement the specific operation.
Then how to jump to another view like webView via the navigationController?
I want to use the prepareForSegue to handle this issue like below, and I just know how to pass data from one viewController to another viewController.
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!){
var channelC:ChannelController=segue.destinationViewController as ChannelController
channelC.delegate = self
//将channelData传递给ChannelController中去。
channelC.channelData=self.channelData
}
I don't know how to code in the didSelectRowAtIndexPath method when I want to show up another view like WebView?
I just use the storyboard to handle viewController switch thing.
Thanks
Here I create a simple example for you :
import UIKit
class ViewController: UIViewController,UITableViewDataSource, UITableViewDelegate {
var arr: [String] = ["google", "yahoo", "Swift"]
var index : Int = Int()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return arr.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var identifier : NSString = "Cell"
var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? UITableViewCell
if !(cell != nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: identifier)
}
cell?.textLabel.text = self.arr[indexPath.row]
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
//store your clicked row into index
index = indexPath.row
// get to the next screen
self.performSegueWithIdentifier("goNext", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "goNext") {
var webViewController = segue.destinationViewController as googleViewController
//switch case for row which you have clicked
switch index{
case 0:
webViewController.url = "https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8"
case 1:
webViewController.url = "https://in.yahoo.com/"
case 2:
webViewController.url = "https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_456"
default:
println("nothing")
}
}
}
}
here is code for your googleViewController.swift
#IBOutlet weak var webView: UIWebView!
var url : String = String()
override func viewDidLoad() {
super.viewDidLoad()
let requestURL = NSURL(string:url)
let request = NSURLRequest(URL: requestURL!)
webView.loadRequest(request)
}
May be this will help you.

creating custom tableview cells in swift

I have a custom cell class with a couple of IBOutlets. I have added the class to the storyboard. I have connected all my outlets. my cellForRowAtIndexPath function looks like this:
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as SwipeableCell
cell.mainTextLabel.text = self.venueService.mainCategoriesArray()[indexPath.row]
return cell
}
Here is my custom cell class:
class SwipeableCell: UITableViewCell {
#IBOutlet var option1: UIButton
#IBOutlet var option2: UIButton
#IBOutlet var topLayerView : UIView
#IBOutlet var mainTextLabel : UILabel
#IBOutlet var categoryIcon : UIImageView
init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
}
When I run the app, all my cell are empty. I have logged out self.venueService.mainCategoriesArray() and it contains all the correct strings. I have also tried putting an actual string equal to the label, and that produces the same result.
What am I missing? Any help is appreciated.
Custom Table View Cell Example
Tested with Xcode 9 (edit also tested on 11 / 12 Beta 2) and Swift 4 (edit: also tested on 5.2)
The asker of the original question has solved their problem. I am adding this answer as a mini self contained example project for others who are trying to do the same thing.
The finished project should look like this:
Create a new project
It can be just a Single View Application.
Add the code
Add a new Swift file to your project. Name it MyCustomCell.swift. This class will hold the outlets for the views that you add to your cell in the storyboard.
import UIKit
class MyCustomCell: UITableViewCell {
#IBOutlet weak var myView: UIView!
#IBOutlet weak var myCellLabel: UILabel!
}
We will connect these outlets later.
Open ViewController.swift and make sure you have the following content:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// These strings will be the data for the table view cells
let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
// These are the colors of the square views in our table view cells.
// In a real project you might use UIImages.
let colors = [UIColor.blue, UIColor.yellow, UIColor.magenta, UIColor.red, UIColor.brown]
// Don't forget to enter this in IB also
let cellReuseIdentifier = "cell"
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell
cell.myView.backgroundColor = self.colors[indexPath.row]
cell.myCellLabel.text = self.animals[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
Setup the storyboard
Add a Table View to your view controller and use auto layout to pin it to the four sides of the View Controller. Then drag a Table View Cell onto the Table View. And then drag a View and a Label onto the Prototype cell. (You may need to select the Table View Cell and manually set the Row Height to something taller in the Size inspector so that you have more room to work with.) Use auto layout to fix the View and the Label how you want them arranged within the content view of the Table View Cell. For example, I made my View be 100x100.
Other IB settings
Custom class name and Identifier
Select the Table View Cell and set the custom class to be MyCustomCell (the name of the class in the Swift file we added). Also set the Identifier to be cell (the same string that we used for the cellReuseIdentifier in the code above.
Hook Up the Outlets
Control drag from the Table View in the storyboard to the tableView variable in the ViewController code.
Do the same for the View and the Label in your Prototype cell to the myView and myCellLabel variables in the MyCustomCell class.
Finished
That's it. You should be able to run your project now.
Notes
The colored views that I used here could be replaced with anything. An obvious example would be a UIImageView.
If you are just trying to get a TableView to work, see this even more basic example.
If you need a Table View with variable cell heights, see this example.
This is for who are working custom cell with .xib
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let identifier = "Custom"
var cell: CustomCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomCel
if cell == nil {
tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: identifier)
cell =tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomCell
}return cell}
I have the same problem.
Generally what I did is the same as you.
class dynamicCell: UITableViewCell {
#IBOutlet var testLabel : UILabel
init(style: UITableViewCellStyle, reuseIdentifier: String) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
and in the uitableviewcell method:
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell :dynamicCell = tableView.dequeueReusableCellWithIdentifier("cell") as dynamicCell
cell.testLabel.text = "so sad"
println(cell.testLabel)
return cell;
}
and yeah the tableview shows nothing! But guess what, it actually shows something...because the log I get from the println(cell.testLabel) shows that all the Labels are actually displayed out.
BUT! their Frames is strange, which have something like this:
frame = (0 -21; 42 21);
so it has a (0,-21) as (x,y), so that means the label just appears at somewhere outside the bound of the cell.
so I try to add adjust the frame manually like this:
cell.testLabel.frame = CGRectMake(10, 10, 42, 21)
and sadly, it doesn't work.
---------------update after 10 min -----------------
I DID IT.
so, it seems that the problem comes from the Size Classes.
Click on your .storyboard file and go to the File Inspector Tab
UNCHECK THE Size Classes checkbox
and finally, my "so sad"Label comes out!
Thanks for all the different suggestions, but I finally figured it out. The custom class was set up correctly. All I needed to do, was in the storyboard where I choose the custom class: remove it, and select it again. It doesn't make much sense, but that ended up working for me.
Last Updated Version is with xCode 6.1
class StampInfoTableViewCell: UITableViewCell{
#IBOutlet weak var stampDate: UILabel!
#IBOutlet weak var numberText: UILabel!
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 awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Details
Xcode Version 10.2.1 (10E1001), Swift 5
Solution
import UIKit
// MARK: - IdentifiableCell protocol will generate cell identifier based on the class name
protocol Identifiable: class {}
extension Identifiable { static var identifier: String { return "\(self)"} }
// MARK: - Functions which will use a cell class (conforming Identifiable protocol) to `dequeueReusableCell`
extension UITableView {
typealias IdentifiableCell = UITableViewCell & Identifiable
func register<T: IdentifiableCell>(class: T.Type) { register(T.self, forCellReuseIdentifier: T.identifier) }
func register(classes: [Identifiable.Type]) { classes.forEach { register($0.self, forCellReuseIdentifier: $0.identifier) } }
func dequeueReusableCell<T: IdentifiableCell>(aClass: T.Type, initital closure: ((T) -> Void)?) -> UITableViewCell {
guard let cell = dequeueReusableCell(withIdentifier: T.identifier) as? T else { return UITableViewCell() }
closure?(cell)
return cell
}
func dequeueReusableCell<T: IdentifiableCell>(aClass: T.Type, for indexPath: IndexPath, initital closure: ((T) -> Void)?) -> UITableViewCell {
guard let cell = dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as? T else { return UITableViewCell() }
closure?(cell)
return cell
}
}
extension Array where Element == UITableViewCell.Type {
var onlyIdentifiables: [Identifiable.Type] { return compactMap { $0 as? Identifiable.Type } }
}
Usage
// Define cells classes
class TableViewCell1: UITableViewCell, Identifiable { /*....*/ }
class TableViewCell2: TableViewCell1 { /*....*/ }
// .....
// Register cells
tableView.register(classes: [TableViewCell1.self, TableViewCell2.self]. onlyIdentifiables)
// Create/Reuse cells
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.row % 2) == 0 {
return tableView.dequeueReusableCell(aClass: TableViewCell1.self, for: indexPath) { cell in
// ....
}
} else {
return tableView.dequeueReusableCell(aClass: TableViewCell2.self, for: indexPath) { cell in
// ...
}
}
}
Full Sample
Do not forget to add the solution code here
import UIKit
class ViewController: UIViewController {
private weak var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
}
}
// MARK: - Setup(init) subviews
extension ViewController {
private func setupTableView() {
let tableView = UITableView()
view.addSubview(tableView)
self.tableView = tableView
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.register(classes: [TableViewCell1.self, TableViewCell2.self, TableViewCell3.self].onlyIdentifiables)
tableView.dataSource = self
}
}
// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int { return 1 }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch (indexPath.row % 3) {
case 0:
return tableView.dequeueReusableCell(aClass: TableViewCell1.self, for: indexPath) { cell in
cell.textLabel?.text = "\(cell.classForCoder)"
}
case 1:
return tableView.dequeueReusableCell(aClass: TableViewCell2.self, for: indexPath) { cell in
cell.textLabel?.text = "\(cell.classForCoder)"
}
default:
return tableView.dequeueReusableCell(aClass: TableViewCell3.self, for: indexPath) { cell in
cell.textLabel?.text = "\(cell.classForCoder)"
}
}
}
}
Results
Uncheck "Size Classes" checkbox works for me as well, but you could also add the missing constraints in the interface builder. Just use the built-in function if you don't want to add the constraints on your own. Using constraints is - in my opinion - the better way because the layout is independent from the device (iPhone or iPad).
It is Purely swift notation an working for me
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cellIdentifier:String = "CustomFields"
var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CustomCell
if (cell == nil)
{
var nib:Array = NSBundle.mainBundle().loadNibNamed("CustomCell", owner: self, options: nil)
cell = nib[0] as? CustomCell
}
return cell!
}
[1] First Design your tableview cell in StoryBoard.
[2] Put below table view delegate method
//MARK: - Tableview Delegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return <“Your Array”>
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
var totalHeight : CGFloat = <cell name>.<label name>.frame.origin.y
totalHeight += UpdateRowHeight(<cell name>.<label name>, textToAdd: <your array>[indexPath.row])
return totalHeight
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell : <cell name>! = tableView.dequeueReusableCellWithIdentifier(“<cell identifier>”, forIndexPath: indexPath) as! CCell_VideoCall
if(cell == nil)
{
cell = NSBundle.mainBundle().loadNibNamed("<cell identifier>", owner: self, options: nil)[0] as! <cell name>;
}
<cell name>.<label name>.text = <your array>[indexPath.row] as? String
return cell as <cell name>
}
//MARK: - Custom Methods
func UpdateRowHeight ( ViewToAdd : UILabel , textToAdd : AnyObject ) -> CGFloat{
var actualHeight : CGFloat = ViewToAdd.frame.size.height
if let strName : String? = (textToAdd as? String)
where !strName!.isEmpty
{
actualHeight = heightForView1(strName!, font: ViewToAdd.font, width: ViewToAdd.frame.size.width, DesignTimeHeight: actualHeight )
}
return actualHeight
}
Set tag for imageview and label in cell
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("imagedataCell", forIndexPath: indexPath) as! UITableViewCell
let rowData = self.tableData[indexPath.row] as! NSDictionary
let urlString = rowData["artworkUrl60"] as? String
// Create an NSURL instance from the String URL we get from the API
let imgURL = NSURL(string: urlString!)
// Get the formatted price string for display in the subtitle
let formattedPrice = rowData["formattedPrice"] as? String
// Download an NSData representation of the image at the URL
let imgData = NSData(contentsOfURL: imgURL!)
(cell.contentView.viewWithTag(1) as! UIImageView).image = UIImage(data: imgData!)
(cell.contentView.viewWithTag(2) as! UILabel).text = rowData["trackName"] as? String
return cell
}
OR
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "imagedataCell")
if let rowData: NSDictionary = self.tableData[indexPath.row] as? NSDictionary,
urlString = rowData["artworkUrl60"] as? String,
imgURL = NSURL(string: urlString),
formattedPrice = rowData["formattedPrice"] as? String,
imgData = NSData(contentsOfURL: imgURL),
trackName = rowData["trackName"] as? String {
cell.detailTextLabel?.text = formattedPrice
cell.imageView?.image = UIImage(data: imgData)
cell.textLabel?.text = trackName
}
return cell
}
see also TableImage loader from github
The actual Apple reference documentation is quite comprehensive
https://developer.apple.com/library/archive/referencelibrary/GettingStarted/DevelopiOSAppsSwift/CreateATableView.html#//apple_ref/doc/uid/TP40015214-CH8-SW2
Scroll down until you see this part