Wednesday, February 20, 2019

Lesson 3 – TableView

Right click to project folder, new file, CoCoa Class, name it third, move cursor to second box to make Next show, Create.
Type import UIKit
Copy in to class
override func viewDidLoad() {
        super.viewDidLoad()
}
Declare a tableView.
var tableView: UITableView!

Set position, add to view, set bacground to view. Copy in to viewDidLoad.
let c = UIScreen.mainScreen().bounds.size.height
tableView = UITableView(frame: CGRect(x: 10, y: 20, width: 325, height: c-50))
 let the = tableView
 the.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "iden")
     the.dataSource = self
     the.delegate = self
     view.backgroundColor = UIColor.whiteColor()
     view.addSubview(the)
Copy to class declaration.
UITableViewDataSource, UITableViewDelegate
Copy array to above viewDidLoad
var fru=["Pear","Banana", "Cashew", "Orange", "Water melon", "Peach", "Grape", "Mango", "Plum" ]

Ignore red mark errors.
Let look at code.
The line let c = UIScreen.mainScreen().bounds.size.height get screen height.
We use this to set table height. Other lines initial table and set background for viewcontrolller.
Copy to above last close bracket.
func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fru.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("iden", forIndexPath: indexPath)
       
        cell.textLabel?.text = fru[indexPath.row]
        cell.textLabel?.font = UIFont(name:"Futura", size:18)
        cell.textLabel?.textColor=UIColor.blueColor()
        //cell.accessoryType = .DisclosureIndicator
        return cell
    }
    func tableView(tableView: UITableView,
                   didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let row = fru[indexPath.row]
        let so = indexPath.row
          
    }
override func prefersStatusBarHidden() -> Bool {
        return true
    }
Back to ViewController.swift, change function of next button to

func next(sender: UIButton){
        let vc = third()
        self.presentViewController(vc, animated: true, completion: nil)
    }
Run to see screen like this.

Let look at code.
Func numberOfSections return one row text for one cell.
Func tableView return fru.count, number of table rows.
Func tableView contain.
cell.textLabel?.text = fru[indexPath.row]
        cell.textLabel?.font = UIFont(name:"Futura", size:18)
        cell.textLabel?.textColor=UIColor.blueColor()
These lines set text to table, custom font and color string.
If want to have an arrow at right, add.
cell.accessoryType = .DisclosureIndicator
Next Func tableView contain two lines.
let row = fru[indexPath.row]
 let so = indexPath.row
Here we code something when user touch row.
Copy toast function to below.
    func toast(t:String){
        let toastLabel = UILabel(frame: CGRectMake(view.frame.size.width/2 - 150, 150, 300, 35))
        toastLabel.backgroundColor = UIColor.blackColor()
        toastLabel.textColor = UIColor.whiteColor()
        toastLabel.textAlignment = NSTextAlignment.Center;
        self.view.addSubview(toastLabel)
        toastLabel.text = t
        toastLabel.alpha = 1.0
        toastLabel.layer.cornerRadius = 10;
        toastLabel.clipsToBounds  =  true
        UIView.animateWithDuration(4.0, delay: 0.5, options: .CurveEaseOut, animations: {
           
            toastLabel.alpha = 0.0
           
            }, completion: nil)
    }
Add to last func tableView
toast("You ‘ve touch row"+row)

Run to see toast when we touch screen.

Now change toast("You ‘ve touch row "+row)
by toast("You ‘ve touch row "+String(so))
Run to see wrong index row, correct it by plus 1 to row index.
If want to delete, edit a row, copy these lines.
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?
   {
        let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete"){(UITableViewRowAction,NSIndexPath) -> Void in
           
            self.fru.removeAtIndex(indexPath.row)
            //delete and reload
            tableView.reloadData()
      }
        let edit = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "Edit"){(UITableViewRowAction,NSIndexPath) -> Void in
            //do something
      }
       
        edit.backgroundColor = UIColor.blackColor()
        return [delete,edit]
    }
Run and swipe on row to see button Delete and Edit.
If we delete and reopen class, it still has all row because it reload array fru, if want compete delete a row, we must change array when reopen class.
Add Quit button to below table.
Copy to above override
var bu1:UIButton!
Copy in to viewDidLoad.
bu1 = UIButton(frame: CGRect(x:100, y: c-35, width: 100, height: 32))
bu1.setTitle("Quit",forState: .Normal)
bu1.backgroundColor = UIColor.lightGrayColor()
bu1.setTitleColor(UIColor.blueColor(), forState: .Normal)
          
       view.addSubview(bu1)
Copy function control button.
func quit(sender: UIButton){
        self.dismissViewControllerAnimated(true, completion: nil)
    }
Connect it to button in viewDidLoad
bu1.addTarget(self, action: #selector(quit(_:)), forControlEvents: UIControlEvents.TouchUpInside)
Run to see result.

Try to center button Quit, use screen width to ajust x index.
let r = view.frame.size.width
Or bu1.center = CGPoint(x: view.center.x, y: c-35)
See the different of two ways when use the same y: c-35
Do all things in code very simple, no need to see storyboard any more.
If do in storyboard, it much more complex with drag and drop, connect, add constraints.

We should never use storyboard, leave it white blank alone.

No comments:

Post a Comment