Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView inside a ViewController with custom cell without storyboard

I'm working with Swift 2.0 and Xcode 7.2.

I want to learn how to make an app without a storyboard (UI with pure programming code). To start off, I am trying to make a simple app, with three labels, inside a custom UITableView cell which will be updated dynamically through the internet.

Here is what I have achieved so far:

  • Created a new Swift project and deleted the main.storyboard from the project
  • Added a view controller as the rootViewController in AppDelegate
  • Included code to create a UITableView inside this view

Here are the other tasks I want to accomplish (all programmatically, without using the attribute inspector):

  • Insert a UINavigationController into the ViewController
  • Add a custom cell with three labels
  • Update the table view with data

If possible, I would want to have the ability to have everything working in landscape mode as well.

Can anyone tell me how to do this?

AppDelegate.swift

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window!.backgroundColor = UIColor.whiteColor()
    window!.rootViewController = ViewController()
    window!.makeKeyAndVisible()
    return true
}

ViewController.swift

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        tableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = UIColor.whiteColor()


        tableView.frame = CGRectMake(0 , 0, self.view.bounds.width, self.view.bounds.height)//Optional for table size

        self.view.addSubview(tableView)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let myCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "myIdentifier")

        myCell.textLabel?.text = "\(indexPath.row)"
        myCell.detailTextLabel?.text = "Subtitle"

        return myCell
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

I have no idea how to create a custom cell programmatically to which I can add objects.

Help would be appreciated.

Thanks.

like image 771
Vicky Arora Avatar asked Jan 07 '23 19:01

Vicky Arora


2 Answers

If you are not using storyboard, you can define your cell just above the class where your ViewController where your are including your tableView something like myCell which is your custom UITableViewCell as given below.

In this myCell, you can add as many objects as your want and set them up in the setUpCell() block.

The full code is as below, please make sure you call setUpCell() when you use your cell's in cellForRowAtIndexPath.

ViewController.swift

import #UIKit

class myCell: UITableViewCell {

    // Define label, textField etc
    var aMap: UILabel!

    // Setup your objects
    func setUpCell() {
        aMap = UILabel(frame: CGRectMake(0, 0, 200, 50))
        self.contentView.addSubview(aMap)
    }
}


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView = UITableView()
    // for ex, lets say, your data array is defined in the variable below
    var dataArray = [[String:AnyObject]]() //Array of your data to be displayed

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        tableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = UIColor.whiteColor()

        // register your class with cell identifier
        self.tableView.registerClass(myCell.self as AnyClass, forCellReuseIdentifier: "Cell")

        self.view.addSubview(tableView)

        dataArray = // Something loaded from internet 
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return flightDataArr.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

       // let myCell = tableView.dequeueReusableCellWithIdentifier("myIdentifier", forIndexPath: indexPath)

        var cell:myCell? = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? myCell

        if cell == nil {
            cell = myCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
        }
        var data = dataArray[indexPath.row]
        cell?.setUpCell()
        cell!.aMap.text = String(dict["productName"])
        return cell!
    }
}

See if this works for you. I never used programming to create tableView, so this may not be the optimal way to create your tableView programmatically. I hope someone else may help you with a better answer if possible.

like image 93
NS1518 Avatar answered Feb 16 '23 01:02

NS1518


You can create a sub class of UITableViewCell say PackageListTableViewCell.

Declare number of labels in tabelViewCell custom class as per your requirements like below,

var label1 : UILabel?;

override init:reuseIdentifier: in custom cell with additional parameters as below.

        override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

            //create labels as per your requirement


           self.label1 = //initialise you label
           //set frame, or constraint
           //set text color, background color etc

            //add created labels to cell as below
           self.contentView.addSubView(self.label1);          

    }

your tableView:cellForRowAtIndexPath: will be look like,

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let lable1String = "lbl1"
        let lable2String = "lbl2"
        let lable3String = "lbl3"

        var cell : PackageListTableViewCell! = tableView.dequeueReusableCellWithIdentifier("cellID") as?PackageListTableViewCell

        if (cell == nil) {
            cell = PackageListTableViewCell.init(style: UITableViewCellStyle.Default,
                reuseIdentifier:"cellID");

        }

        cell.selectionStyle = UITableViewCellSelectionStyle.None;
        //set text of your lables as below
        cell.label1.text = lable1String;

        return cell;
    }
like image 30
Hitendra Solanki Avatar answered Feb 15 '23 23:02

Hitendra Solanki