Showing posts with label table. Show all posts
Showing posts with label table. Show all posts

Thursday, May 19, 2016

Horizontal Adjustment for Table Separator Lines

This example uses Xcode 7.3.1 (Swift 2.2) and iOS 9.3 simulator.

The default separator line in a tableView is like this:


Gaps exist at the left of the separator lines, white the right side of the horizontal lines touch the screen edge.

To eliminate the gaps at the left, add these lines:


tableView.separatorInset = UIEdgeInsetsZero

tableView.layoutMargins = UIEdgeInsetsZero

and this:


cell.layoutMargins = UIEdgeInsetsZero

Result:




To add gaps to the right of separators, simply add this line:


tableView.separatorInset.right = tableView.separatorInset.left

Result:



The separator lines are now centered.

Related Information:

White space before separator line into my TableView

iOS 8 UITableView separator inset 0 not working

Draw UITableView programmatically (without using the Storyboard)

Monday, November 9, 2015

scrollViewDidScroll - Pull up table to refresh content and change the table background color

Update: December 10, 2016 (Xcode 8.1 and Swift 3.0.1)

Original Post: November 9, 2015

This example shows how to:

1. Refresh the table view by adding ten extra rows while pulling the table up to the bottom.
2. Change the table background color for every 10 rows.

Note: This example does not include the activity indicator.

Edit ViewController.swift as below:

Xcode 8.1 and Swift 3.0.1:


import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var tableView : UITableView!
    var tableRowNumber : Int = 10
    
    //Colors used in the table
    var colorArray = [UIColor.yellow, UIColor.orange, UIColor.cyan, UIColor.lightGray, UIColor.white]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView = UITableView(frame: CGRect(x: 0, y: 30, width: view.bounds.width, height: 300))

        tableView.dataSource = self
        tableView.delegate = self
        
        //Disable the default bouncing feature.
        tableView.bounces = false
        
        view.addSubview(tableView)
        
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableRowNumber
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "myIdentifier")
        cell.textLabel?.text = "Row \(indexPath.row)"
        
        //Change the table background color for every 10 rows.
        let color = colorArray[(indexPath.row/10)%colorArray.count]
        cell.backgroundColor = color
        
        return cell
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //If we reach the end of the table.
        if ((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height)
        {
            //Add ten more rows and reload the table content.
            tableRowNumber += 10
            tableView.reloadData()
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Original Post: November 9, 2015

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var tableView : UITableView!
    var tableRowNumber : Int = 10
    
    //Colors used in the table
    var colorArray = [UIColor.yellowColor(), UIColor.orangeColor(), UIColor.cyanColor(), UIColor.lightGrayColor(), UIColor.whiteColor()]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView = UITableView(frame: CGRectMake(0, 30, view.bounds.width, 300))
        tableView.dataSource = self
        tableView.delegate = self
        
        //Disable the default bouncing feature.
        tableView.bounces = false
        
        view.addSubview(tableView)
        
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableRowNumber
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "myIdentifier")
        cell.textLabel?.text = "Row \(indexPath.row)"
        
        //Change the table background color for every 10 rows.
        let color = colorArray[(indexPath.row/10)%colorArray.count]
        cell.backgroundColor = color
        
        return cell
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //If we reach the end of the table.
        if ((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height)
        {
            //Add ten more rows and reload the table content.
            tableRowNumber += 10
            tableView.reloadData()
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Result:


==========================
Related Post:

Saturday, November 7, 2015

UIRefreshControl - Pull down to refresh for the UITableView

This post shows how to refresh table by pulling down without using UITableViewController. An activity indicator is shown above the table while pulling it down. Tested with Xcode 6.4 and 7.1.

Edit ViewController.swift as below:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var tableView : UITableView!
    var tableRowNumber : Int = 5
    var refreshControl : UIRefreshControl!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView = UITableView(frame: CGRectMake(0, 30, view.bounds.width, 400))
        tableView.dataSource = self
        tableView.delegate = self
        
        view.addSubview(tableView)
        
        refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: Selector("enlargeTable"), forControlEvents: UIControlEvents.ValueChanged)
        tableView.addSubview(refreshControl)
    }
    
    func enlargeTable() {
        tableRowNumber += 5
        tableView.reloadData()
        refreshControl.endRefreshing()
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableRowNumber
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "myIdentifier")
        cell.textLabel?.text = "\(indexPath.row)"
        
        return cell
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    

}

=========================
Related Post:

Saturday, September 19, 2015

CGAffineTransformMakeRotation - Create a horizontal table programmatically

This post has been updated with Xcode 7.3 (Swift 2.2) on April 6, 2016.

1. Edit ViewController.swift as:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var tableView : UITableView!
    //Table cell background color
    let colorArray = [UIColor.lightGrayColor(), UIColor.darkGrayColor(), UIColor.yellowColor(), UIColor.cyanColor(), UIColor.purpleColor()]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let frame = CGRectMake(0, view.bounds.height/2, view.bounds.width, view.bounds.height/2)
        //A more correct way is to set the frame 
        //as CGRectMake(0, view.bounds.height/2, 
        //view.bounds.height/2view.bounds.width) here,
        //i.e. swap the width/height values
        //before rotation.
        tableView = UITableView(frame: frame)
        tableView.delegate = self
        tableView.dataSource = self
        
        //Remove gaps at margins #1
        if tableView.respondsToSelector(Selector("separatorInset")) {
            tableView.separatorInset = UIEdgeInsetsZero;
        }
        
        if tableView.respondsToSelector(Selector("layoutMargins")) {
            tableView.layoutMargins = UIEdgeInsetsZero;

        }
        
        tableView.transform = CGAffineTransformMakeRotation(-CGFloat(M_PI_2))

        //Set the frame size again after rotation.
        tableView.frame = frame
        view.addSubview(tableView)
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "myIdentifier")
        
        cell.textLabel?.text = "Cell #\(indexPath.row)"
        cell.detailTextLabel?.text = "Subtitle"
        cell.backgroundColor = colorArray[indexPath.row]
        cell.contentView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
        
        //Remove gaps at margins #2
        if cell.respondsToSelector(Selector("separatorInset")) {
            cell.separatorInset = UIEdgeInsetsZero;
        }
        
        if cell.respondsToSelector(Selector("preservesSuperviewLayoutMargins")) {
            cell.preservesSuperviewLayoutMargins = false;
        }
        
        if cell.respondsToSelector(Selector("layoutMargins")) {
            cell.layoutMargins = UIEdgeInsetsZero;
        }
        
        return cell

    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        return view.bounds.width/3
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

2. Run the iOS simulator to get the result:


Tuesday, September 15, 2015

UITableViewCell - Create Custom Prototype Table Cell in UITableView Programmatically (without using the Storyboard)

Update: July 13, 2017 - Xcode 8.3.3 + Swift 3.1
Original Post: September 15, 2015
===============

Update: July 13, 2017 - Xcode 8.3.3 + Swift 3.1

1. Create a new file called MyTableViewCell.swift as:


import UIKit

class MyTableViewCell: UITableViewCell {
    
    var myLabel1: UILabel!
    var myLabel2: UILabel!
    var myButton1 : UIButton!
    var myButton2 : UIButton!
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:)")
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        let gap : CGFloat = 10
        let labelHeight: CGFloat = 30
        let labelWidth: CGFloat = 150
        let lineGap : CGFloat = 5
        let label2Y : CGFloat = gap + labelHeight + lineGap
        let imageSize : CGFloat = 30
        
        myLabel1 = UILabel()
        myLabel1.frame = CGRect(x: gap, y: gap, width: labelWidth, height: labelHeight)
        myLabel1.textColor = UIColor.black
        contentView.addSubview(myLabel1)
        
        myLabel2 = UILabel()
        myLabel2.frame = CGRect(x: gap, y: label2Y, width: labelWidth, height: labelHeight)
        myLabel2.textColor = UIColor.black
        contentView.addSubview(myLabel2)
        
        myButton1 = UIButton()
        myButton1.frame = CGRect(x: bounds.width-imageSize - gap, y: gap, width: imageSize, height: imageSize)
        myButton1.setImage(UIImage(named: "browser.png"), for: UIControlState.normal)
        contentView.addSubview(myButton1)
        
        myButton2 = UIButton()
        myButton2.frame = CGRect(x: bounds.width-imageSize - gap, y: label2Y, width: imageSize, height: imageSize)
        myButton2.setImage(UIImage(named: "telephone.png"), for: UIControlState.normal)
        contentView.addSubview(myButton2)
    }

}


2. Modify ViewController.swift as:


import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var myArray = ["AAA", "BBB", "CCC", "DDD"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tableView = UITableView(frame: view.bounds, style: UITableViewStyle.grouped)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 85
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MyTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "myIdentifier")
        cell.myLabel1.text = myArray[indexPath.row]
        cell.myLabel2.text = "\(indexPath.row)"
        cell.myButton1.addTarget(self, action: #selector(pressedBrowser(sender: )), for: UIControlEvents.touchUpInside)
        cell.myButton2.addTarget(self, action: #selector(pressedTelephone(sender: )), for: UIControlEvents.touchUpInside)
        return cell
    }
    
    func pressedBrowser(sender: UIButton) {
        print("pressedBrowser")
    }
    
    func pressedTelephone(sender: UIButton) {
        print("pressedTelephone")
    }
}
3. The result is:



Original Post: September 15, 2015


1. Create a new file called MyTableViewCell.swift as:

import UIKit

class MyTableViewCell: UITableViewCell {

    var myLabel1: UILabel!
    var myLabel2: UILabel!
    var myButton1 : UIButton!
    var myButton2 : UIButton!
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:)")
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        let gap : CGFloat = 10
        let labelHeight: CGFloat = 30
        let labelWidth: CGFloat = 150
        let lineGap : CGFloat = 5
        let label2Y : CGFloat = gap + labelHeight + lineGap
        let imageSize : CGFloat = 30
        
        myLabel1 = UILabel()
        myLabel1.frame = CGRectMake(gap, gap, labelWidth, labelHeight)
        myLabel1.textColor = UIColor.blackColor()
        contentView.addSubview(myLabel1)
        
        myLabel2 = UILabel()
        myLabel2.frame = CGRectMake(gap, label2Y, labelWidth, labelHeight)
        myLabel2.textColor = UIColor.blackColor()
        contentView.addSubview(myLabel2)
        
        myButton1 = UIButton()
        myButton1.frame = CGRectMake(bounds.width-imageSize - gap, gap, imageSize, imageSize)
        myButton1.setImage(UIImage(named: "browser.png"), forState: UIControlState.Normal)
        contentView.addSubview(myButton1)
        
        myButton2 = UIButton()
        myButton2.frame = CGRectMake(bounds.width-imageSize - gap, label2Y, imageSize, imageSize)
        myButton2.setImage(UIImage(named: "telephone.png"), forState: UIControlState.Normal)
        contentView.addSubview(myButton2)
    }

}

2. Modify ViewController.swift as:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var myArray = ["AAA", "BBB", "CCC", "DDD"]

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tableView = UITableView(frame: view.bounds, style: UITableViewStyle.Grouped)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
    }

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

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 85
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell = MyTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "myIdentifier")
        cell.myLabel1.text = myArray[indexPath.row]
        cell.myLabel2.text = "\(indexPath.row)"
        cell.myButton1.addTarget(self, action: "pressedBrowser:", forControlEvents: UIControlEvents.TouchUpInside)
        cell.myButton2.addTarget(self, action: "pressedTelephone:", forControlEvents: UIControlEvents.TouchUpInside)
        return cell
    }

    func pressedBrowser(sender: UIButton) {
        println("pressedBrowser")
    }
    
    func pressedTelephone(sender: UIButton) {
        println("pressedTelephone")
    }
}

3. The result is:


========================================