ios-lynda


Ctrl+Shift+Click to be able to select any control from hierarchy on top of each other




You can right click on main.storyboard open as Interface Builder vs Source code to view XML of the storyboard

view > show utilities > bject library
drag and drop a label
in the atribute inspector change properties
run it as iphone 5


preferences > text editing > show line number

UI  ---> acition happens  ---> call @IBAction method
if you put @IBAction in front of a method. you make it callable from a view object (IB==Interface builder)

programatically ----> outlet  ---> e.g. a label
define the label to be an outlet. and in the code we would mark ### to mark a piece of our code to be connectable to a view object in a user interfacefile.


app that has a text field a label a button. on button click change label to the content of text field
one code has to get data from textfield. one code sets label : two outlets. whether getting or setting we are starting from code
button invokes code: action

click Show Assitant editor to view two panes in the editor
Ctrl drag from button to ViewController class.
Name: changeLabel
connection: Action  //make sure it s action

Ctrl drag from text field to ViewController class.
Name: simpleTextField

Ctrl drag from label to ViewController class.
Name: simpleLabel

in the changeLabel action
        simpleLabel.text = "Hello " + simpleTextField.text

So this was controller and view interaction. Where is model?
from time to time different pats of the UI have differnet priorities: First respnder is the most important one
you can programatically specify which object is fisrt responder

To make hte keyboard go away on
clicking button
by talking to  the textfield. All the behavio is driven by text field. A keyboard automatically showed up because textfield became first reponder. In changelabel method add:
 self.simpleTextField.resignFirstResponder()
clicking on a blank part of screen
make an invisible button at teh background so when user touches you catch action OR
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        self.view.endEditing(true)
    }    
clicking return key
Use delegate outlet.
The whole idea of delegate is as follows:
1. A calls object B to perform an action
2. A implements the delegate interface method
3. B has a reference to A
4. B calls A's method when done

a helper object, known as a delegate (ViewControl), is given the responsibility to execute a task for the delegator.
delegate def: someone that represents someone else e.g. in a conference

So delegate is like delegate providing a call back for delegator which delegator calls when done. as in other languages.


Click on Connecitons Inspector: How these user interface pieces connect to other parts of the project. you can use it to se the connection already made by Ctrl drags we made so far to ViewController. if you click on button touch Up Inside is marked which means the user touches the button and by the time lift the finger it is still in the boundary of hte button
delegate outlet means textfield is a generic textfield that I want some part of application to perform some work on its behalf

delegate methods are optional. it is like a listener

Click on text field. from Connections Inspector tab, drag from Outlets> delegate to yellow circle with white square icon with tooltip View Controller.
This creates a delegate line for textfield inside mainstory xml file and sets the ViewControl class as its destination. (keep a reference of the interested party)

This causes textfield to send itself as delegate to ViewControl
so the view control file is hte delegate for the textfield object. It means text field has several methods it tries to automatically call when various actions happen on text field. begin editing, finish editing, etc. or somebody clicks the clear button on keyboard or return button and that text field tries to call these methods and view control is voluntering to implement those and act as its delegate.



now implement UITextFieldDelegate to have the signatures and autosuggestions but you dont have to.
click on UITextFieldDelegate and view its help documents to see what call backs it can support, we want textFieldShouldReturn
set its code to
textField.resignFirstResponder()
return false
you can see that you get same performace even if you remove the dlegate protocol


you can change the look of return button to Do or done, or ...

They can delegate some responsibility to some of those other classes instead of doin it themselves

.


you can connect the UI and code (action, outlet) from both ways, fom code to ui or ui to code. make sure the circles by the code are filled-in (actually connected). in case of error inspect connections




Click on Document Outline for mainstory and see the hierarchy of the objects in UI


Ctrl drag from one UI item to another to create reletive positioning


Basic iOS UI

The arrow shoes the main view even if you have multiple screens
Open Document outline (tree view) in storyboard
click on view controller in tree
In the utilities pane click on Attributes Inspector tab
Check mark Is initial view controller
In the utilities pane click on Identity Inspector
points to the ViewController class (swift file) that controlls this view. (connects story board to code file)

Auto Layout Constraints (NSLayoutConstaint can do the same thing programatically)
Ctrl drag from one view object to another to relatively position them
e.g. Ctrl drag from one button to the right side fo screen  and you see parent view being highlighted
Click Trailing Space to Container Margin
To view the UI warning
Click on yellow Alert sign on the kinda URL section to view the warning
OR in the UI tree click on the little white arrow icon in red circle
You need to also specify Y constraint as well not just X
Ctrl drag from it to the top
click Top Space to: Top Layout Guide  (Top Layout Guide (aware of top status bar)and Top Buttom Guide show up for every view controller)
OR use Pin in the Interface Builder window
Click on e.g. button
click on Pin
click on  lines to nearest neighbor for the middle rectangle


Constrainst show up as a node in the tree viewer

You can delete constraints from the tree viewer or by cliking on them in the Interface Builder or by clicking on Resolve Auto Layout Issues small triangle in the lower right corner of the Interface Builder, click clear constraints
Clear Constraints > Add Missing Constraints (to let auto adjust them)    [try Reset To Sugested Constraints]


To preview how layout appears on various other devices

Click on Assistant Editor
In the kinda URL area change from Automatic to Preview
Click little + sign at lower left corner to add more previews
Select one and hit delete to remove it

Landscape preview mode keeps the status bar on

Example
Add DatePicker > Reset To Sugested Constraints > Add button in center under it > Reset To Sugested Constraints > Assitant Mode > Ctrl drag button to code to create action displayDay > Ctrl drag DatePicker to create outlet datePicker to enable getting its content >
        var chosenDate = datePicker.date
       
        var formatter = NSDateFormatter()
        formatter.dateFormat = "EEEE"
       
        let day = formatter.stringFromDate(chosenDate)
        let result = "That was a \(day)"
       
        let alert = UIAlertController(title: result, message: nil, preferredStyle: UIAlertControllerStyle.Alert)
        self.presentViewController(alert, animated: true, completion: nil)
> Add action to the alert to be able to capture dismiss
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

Reset To Sugested Constraints = option shift command =
Example - Configuring a Custom Picker Control
Add Picker > click on ? tab to see info about it. and see what protocols must be provided for it. [Specify delegate, specify data source] > add protocols UIPickerViewDataSource, UIPickerViewDelegate > click on ? to see help and the reference and add the required methods
    let moodArray = ["Happy", "Sad", "Maudlin", "Ecstatic", "Overjoyed", "Optimistic", "Bewildered", "Cynical", "Giddy", "Indifferent", "Relaxed"];
   
   
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
   
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return moodArray.count
    }
   
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        return moodArray[row]
    }
> Click on main.story > click on Connecitons Inspector  > drag from data source to the white square in yellow circle in the top of Interface Builder. Do the same for delegate


> delegate changes to the picker in the ViewControl
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        var newBackgroundColo : UIColor

        switch row {
        case 0,3,4,5,8 :
            newBackgroundColo = UIColor.yellowColor()
        case 1,2 :
            newBackgroundColo = UIColor.darkGrayColor()
        case 6,7,9 :
            newBackgroundColo = UIColor.lightGrayColor()
        default :
            newBackgroundColo =  UIColor(red: 200/255, green: 1.0, blue: 200/255, alpha: 1.0)
        }
       
        self.view.backgroundColor = newBackgroundColo
    }

option , mouse click to view popup help
option, mouse double click to directly go to the help page.

drag and drop your images to assets.
In tree of ui items you have they show in order as in tree, if they over lap reorder them in tree

Visual effect view blurs background, and it has a view itself and you can drag elements into that, and it will non-blured



you can add gestures and for them add delegates to do what they are supposed to do. it will be added to the top of interface builder

{{{{Apple's human interface guide}}}}


Application Life Cycle

AppDelegate.swift
@UIApplicationMain defines this as starting point of app
UIApplicationMain is a builtin function in iOS that creates a standard object called UIApplication that represents a typical iOS application. The basic processing that every iOS app is going to need. Setting up a run loop so the application stays active     and it continues to respond to events and it doesn't just terminate.
info.plist
mainstoryboard file
launch screen intrface

So in the life cycle of a typical iOS application in Swift, the @UIApplicationMain marker will cause the standard UIApplication object to be instantiated. But the thing is our app is different from some generic application object. and we need to say how. how do we add different behavior at application level. In a lot of systems you would use inheritance for this. Inheritance from a provided application class and extend it. but we don't use inheritance for this in iOS we use delegation again. we have a separate class in our project that acts as the delegate for the standard built-in iOS application object and that's our ApDelegate.swift file. so an object of that class is instantiated and the standard ui application object is pointed to our app delegate to have any extra behavior we need to our application level. like our application starting and the application terminating. so we can write some custom coe if we want to in those circumstances, but we are not done by launch , because this application main function then reads the info.plist file to load some configuration information including hte name of a launch scren file if there is one and the main.storyboard file. Up to this part fo the proceess we have no user interface yet. this is all being done in the backgound in a blink of an eye. but one of hte things that the app delegate references to is an object called uiwindow that 's automatically created as part fo th e process. now think about it. the window is clear and transparent but it has a certain size. has boundaries, and thats whatis happening in ios. this UIWindow object represents the boundarie of an iohone or ipad screen. so this window opbject is created as part of the process and it will exist for the lifetime of our application htere is just one window object. but it's transparent we need some content on it. well if we want a launch screen or a launch image defined then that was defined in info.plist that it's read in and that would be loaded in to that window just for momentry zoom in from teh ios home screen. for hte story bard and any asociated view controllers  are also being loaded and they will be loaded into that ui window to provide that initial real user interface nwo if we have a single view user interface we are laoding a single view controller into the window but in more compex applications we will be switching differnet view controllers in and out of that same ui window


 
 







load application
In AppDelegate - application didFinishLaunchingWithOptions
In ViewController - viewDidLoad
In AppDelegate - applicationDidBecomeActive

In AppDelegate - applicationWillResignActive    Presed home button
In AppDelegate - applicationDidEnterBackground
In AppDelegate - applicationWillEnterForeground    press app icon again (app had not terminated)
In AppDelegate - applicationDidBecomeActive

In AppDelegate - applicationWillResignActive
In AppDelegate - applicationDidEnterBackground
In AppDelegate - applicationWillEnterForeground
In AppDelegate - applicationDidBecomeActive

viewwillapear (load data before view loads), viewdidapaer (load viw first for animation then data)


Background functionalty has to be enabled


After running an app, click on Debug View Hierarchy button at teh buttom of the window to view a 3D mode of the UI


Command-b to build
command-r to run

Table Views


drag and drop a TableView>Click on Table > Click on Connections Inspector > drag from Data Source and delegate to the yello circle with white squarein the top of Interface Builder > add protocol UITableViewDataSource, UITableViewDelegate
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
   
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
       // var cell = UITableViewCell()  //old approach
                 var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell    //identifier of cell
        cell.textLabel.text = "Hello"
       
        return cell
    }

OR add data from an array
let devCourses = [
("iOS App Dev with Swift Essential Training","Simon Allardice"),
("iOS 8 SDK New Features","Lee Brimelow"),
("Data Visualization with D3.js","Ray Villalobos"),
("Swift Essential Training","Simon Allardice"),
("Up and Running with AngularJS","Ray Villalobos"),
("MySQL Essential Training","Bill Weinman"),
("Building Adaptive Android Apps with Fragments","David Gassner"),
("Advanced Unity 3D Game Programming","Michael House"),
("Up and Running with Ubuntu Desktop Linux","Scott Simpson"),
("Up and Running with C","Dan Gookin") ]

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

        let (courseTitle, courseauthor) = devCourses[indexPath.row]
        cell.textLabel.text = courseTitle
       
        return cell
    }

Reuse dequeued cells:
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell    //identifier of cell

        let (courseTitle, courseauthor) = devCourses[indexPath.row]
        cell.textLabel.text = courseTitle
       
        return cell
    }
click on table > From attribute Inspector change prototype cells to 1 > Click on the created cell > set identifier to cell

Sections is Table Views
    let devCourses = [  //array of tuples
        ("iOS App Dev with Swift Essential Training","Simon Allardice"),
        ("iOS 8 SDK New Features","Lee Brimelow"),
        ("Data Visualization with D3.js","Ray Villalobos"),
        ("Swift Essential Training","Simon Allardice"),
        ("Up and Running with AngularJS","Ray Villalobos"),
        ("MySQL Essential Training","Bill Weinman"),
        ("Building Adaptive Android Apps with Fragments","David Gassner"),
        ("Advanced Unity 3D Game Programming","Michael House"),
        ("Up and Running with Ubuntu Desktop Linux","Scott Simpson"),
        ("Up and Running with C","Dan Gookin") ]
   
    let webCourses = [
        ("HTML Essential Training","James Williamson"),
        ("Building a Responsive Single-Page Design","Ray Villalobos"),
        ("Muse Essential Training","Justin Seeley"),
        ("WordPress Essential Training","Morten Rand-Hendriksen"),
        ("Installing and Running Joomla! 3: Local and Web-Hosted Sites","Jen Kramer"),
        ("Managing Records in SharePoint","Toni Saddler-French"),
        ("Design the Web: SVG Rollovers with CSS","Chris Converse"),
        ("Up and Running with Ember.js","Kai Gittens"),
        ("HTML5 Game Development with Phaser","Joseph Labrecque"),
        ("Responsive Media","Christopher Schmitt") ]

   
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {return devCourses.count}
        else{return webCourses.count}
    }
   
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
        if indexPath.section == 0{
            let (courseTitle, courseauthor) = devCourses[indexPath.row]
            cell.textLabel.text = courseTitle
        }else{
            let (courseTitle, courseauthor) = webCourses[indexPath.row]
            cell.textLabel.text = courseTitle
        }
        return cell
    }
   
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0{
         return "Developer Courses"
        }else{return "Web Courses"}
    }
 Click on cell > Change Style to Subtitle                    cell.detailTextLabel?.text=courseauthor

Add images to assets: New image set >
   var myImage = UIImage(named: "myCellIcon")
        cell.imageView.image = myImage

Add little arrow: For the cell in the Accessory set Disclosure Indicator


Tabbed Application
In main.storyboard right click on a blank area and set zoom to 50%
The initial ciew controller is a tabbed bar controller (just tabbed bar at buttom), and we have two views which are gong to be embedded there.
To add a tab
drag a view controller to main.storyboard
drag a  label to it
Click Editor, click Size to Fit Content
option shift command =
 Ctrl drag from initial view to the one we just added Click View Controller
Add a new Cocoa Touch class to act as its viewControl class
On the viewcontroller little icon of the view click and click on Identity Inspector
 viewDidLoad, viewWillAppear, ViewWillDisapear




Master Detail
master detail demo



StoryBoard

define flow between multiple screens in an application and hte relationsips between them
before storyboard we would build our story one screen at a time via .xib files
.xib for one screens like launch screens that dont have to be connected to anything else
but now story boards are recommended
xib is compiled to .nib at build time



Add multiple viewControls to story board, add a button t each, Ctrl drag from button to the next viewcontrol
Click first virecontrol, Edit > Embed in Navigation Controller (adds a navigation controller as the initial view controller)




PhotoViewer A table of image names, image itself, image notes
Create Sinlge Page App
Delete the iniitial view controler in the main.storyboard
delete the ViewController.swift
Drag a table view controller to teh main.storyboard
In Attribute Inspector set is initial view controller
Drag a view controller to show the image
Drag a view controller to show the image notes
Ctrl drag from prototype cell to the next view
Add a image viewer to the view and a button to click to see notes
instead fo a button put a toolbar at the buttom
from toolbar Ctrl drag to the next view and select Present Modally view to display from buttom
include all the view controllers in a navigation controller as before. (embed ...)
change background color of last view and add a label, set its mlines to 0 to remove any limitations on notes lengths we might add, also put down a button and call it ok
Double click the navigation bar on first view and set it to Photos

Add a new Swift File called Photo
create struct Photos (as capable as class) with three string members: name,note,path
Add a CocoaTouch class for each view, subclass UIViewController (PhotoTableViewController subclass UITableViewController, DisplayViewController : UIViewController, InfoViewController: UIViewController)
because we added a TableView, we'd better use UITableViewController to have some added functionality
Connect storyboards to these UIViewControllers
Click the small yello circle in storyboard for each view control and in the identity inspector class section select the relevant one

Click on assets and drag and drop a bunch of images to display there

Add logic for each ui
    var photos = [Photo]()  // an array of photos

    var currentPhoto:Photo? //because we dont have a value for it yet we set it to optional to avoid not initialized complaint for now
Ctrl drag from imageviewer to the viewcontroller to make an outlet for it there call the outlet currentImage


Add outlet for notes label called detailsLabel

Fill up with data
in the viewDidLoad() initialize the [Photo] with a bunch of relevant texts
var newPhoto = Photo(name: "Emerald Bay", filename: "emeraldbay", notes: "Emerald Bay, one of Lake Tahoe's most popular and photogenic locations.")
        photos.append(newPhoto)
       
        newPhoto = Photo(name: "A Joshua Tree", filename: "joshuatree", notes: "A Joshua Tree in the Mojave Desert")
        photos.append(newPhoto)
       
        newPhoto = Photo(name: "Sunset in Ventura", filename: "sunset", notes: "Romantic sunset at the beach")
        photos.append(newPhoto)
       
        newPhoto = Photo(name: "Snowman at Lake Tahoe", filename: "snowman", notes: "Lake Tahoe gets 400 inches of snow every year.")
        photos.append(newPhoto)
       
        newPhoto = Photo(name: "Red Rock", filename: "redrock", notes: "Spectacular formations at Red Rock Canyon State Park")
        photos.append(newPhoto)

set table delegates
 numberOfSectionsInTableView return 1
 numberOfRowsInSection return photos.count
 cellForRowAtIndexPath
make sure cell identifier in storyboard is hte same as autocompleted code cell id "photoCell"

        var currentPhoto = photos[indexPath.row]
        cell.textLabel.text = currentPhoto.name

[[CODE IS RUNNABLE AT THIS STAGE]]

Set the data to be passed between views
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
}


// in tableVC
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        var secondScene = segue.destinationViewController as DisplayViewController
        // Pass the selected object to the new view controller.
        if let indexPath = self.tableView.indexPathForSelectedRow(){
            let selectedPhoto = photos[indexPath.row]
            secondScene.currentPhoto = selectedPhoto
        }
    }

// in displayVC
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        var secondScene = segue.destinationViewController as InfoViewController
        // Pass the selected object to the new view controller.
        secondScene.currentPhoto = currentPhoto
    }

    override func viewDidLoad() {
        super.viewDidLoad()
       
        var image = UIImage(named: currentPhoto!.filename)
        currentImage.image = image

        self.title = currentPhoto?.name
    }

// in infoVC
        detailsLabel.text = currentPhoto?.notes


Ctrl drag from ok button to create dismiss action. because it is modal
    @IBAction func dismiss(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }


click on teh segue between display and info and change transition to partial curl or flip horizontal


Developing for an iPad

New UI elements
split-view
for nested data, some knd of master detail relationship
create splitview controller, create master view controller, create detail view controller, load them in splitVC
each pane can have itseown navigation stack

splitVC will tak care of converting master to popover itself.

popovers
switching from landscape mode to portrait mode that only shows detail, popover kinda shows previous hierarchu options like a popup menu. two pane



modal views
screens show, dim the background and ask us to make action befre it goes away. usully for tutorials or options when application first loads, or user passwords
add two views one with a button. Ctrl drag from button to the next and select Present modally
select segue change presentation to form sheet
button action : self.dismissviewcontrolleranimated


Support all orientations
Compatibility mode is not a technique


Size Classes

Regular, Compact
One size class for height and one for width




To set size class in main.storyboard click on wAny hAny

options
Add/remove views
change a font
change a value of a constraint
Add/remove constraint

work on size after autolayout is done
command delete to remove a constraint from a specifci size class
or click on ui object of interest and click on attribute inspector at buttom click the little plus sign beside installed. to remove an object from a specific orientation if it doesnt fit
command delete an object in specific size class nce all the constraints depending on it have been deleted
Ctrl drag one ui element to another in the tree

click the little plus by fonr to set font for specific size class


launch screen

is supposed to be the original app's view without data

Custom Table View cell
Create Single view app
add table view
Add table view cell
Add two labels and a uiimage
new cocoatouch class CustomCell sublass of UITableViewCell
move it among all other files
Click the table view cell in the storboard, set its class to CustomCell
set Restoration id to Cell
set reuse identifier to Cell
go to assitant editor and change automatic to CustomCell
Ctrl drag labels and image to create outlets and call them leftLabel, rightLabel, myImageView
Change automatic to ViewController.swift
Ctrl drag table view to add its outlet called myTableView

Create Person class as swift file and move it among other files
 
import Foundation

class Person{
   
    var name="name"
    var number = 0
    var imageName = "blank"
   
    init(name:String, number:Int, imageName:String){
        self.name = name
        self.number = number
        self.imageName = imageName
    }
}

in ViewController class
    var arrayOfPersons : [Person] = [Person]()

in viewdidload
        setupPersons()
in setupPersons
func setupPersons(){
        var person1 = Person(name: "Ana", number: 60, imageName: "swift 1.jpg")
        var person2 = Person(name: "Joe", number: 10, imageName: "swift 2.jpg")

        arrayOfPersons.append(person1)
        arrayOfPersons.append(person2)       
    }

Right click on tableview and drag from datasource and delegate to the yello circle of mainstory for view controller
OR you can programatically do it, in viewDidLoad
add protocols UITableViewDelegate, UITableViewDataSource
 and in viewdidload
        myTableView.delegate = self
        myTableView.dataSource = self

Command click on uitableviewdatasource shows which methods are not optional to be implemented
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrayOfPersons.count
    }
   
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        let cell :CustomCell = myTableView.dequeueReusableCellWithIdentifier("Cell") as CustomCell
       
        cell.leftLabel.text = arrayOfPersons[indexPath.row].name
        cell.rightLabel.text = "\(arrayOfPersons[indexPath.row].number)"
        cell.imageView.image = UIImage(named: arrayOfPersons[indexPath.row].imageName)
       
        return cell

    }
   





swipe left to delete
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete{
            arrayOfPersons.removeAtIndex(indexPath.row)
            myTableView.reloadData()
        }
    }

if delete key doesnt show, click on table view Editor>Resolve AutoLayout Issues>Reset to Suggested Constraints

Add Detail View
Add a view controller to story board with two labels and an image
Add a viewcontroller call it DetailViewController
in the storyboard identity inspector change class of the new view to DetailViewController, the same thing goes to Storyboard ID
create outlets nameLabel, ageLabel, myDetailImageView
 @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var ageLabel: UILabel!
    @IBOutlet weak var myDetailImageView: UIImageView!
   
    var nameString: String?
    var ageInt : Int?
    var myDetailImageName:String?
In view didload set these
  nameLabel.text=nameString
        ageLabel.text = String(ageInt!)
        myDetailImageView.image = UIImage(named: myDetailImageName!


load the view on select row

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let person  = arrayOfPersons[indexPath.row]
        var detailViewController :DetailViewController = self.storyboard?.instantiateViewControllerWithIdentifier("DetailViewController") as DetailViewController // use the same that was used in the storyboard id of the view in storyboard.
       
        detailViewController.nameString = person.name
        detailViewController.ageInt = person.number
        detailViewController.myDetailImageName = person.imageName
       
        self.presentViewController(detailViewController, animated: true, completion: nil)
    }

In the detailviewcontroller
  override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }





Search Bar
Ctrl drag from Search bar to add it as outlet > from the connections of search bar drag from delegate to yello circle with white square > Impmenet UISearchBarDelegate
    func searchBar(searchBar: UISearchBar, textDidChange searchText: String){
            println(searchText)
            productsArr = Product.FACTORY_INITIALIZED.getInitList()
            if !searchText.isEmpty{
                productsArr = productsArr.filter({$0.name.lowercaseString.rangeOfString(searchText.lowercaseString) != nil})
            }
            productsTable.reloadData()
    }



Auto adjust cell height
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
With just two lines of code, you instruct the table view to calculate the cell’s size matching its content and render it dynamically.




UIScrollView
select the view controller, click on Attribute inspector change, change size to freeform > click on Size inspector and change width and height as you wish > add scroll view.
To disable horizontal scroll impement UIScrollViewDelegate > Ctrl drag from scroll view to yello circle with white rectangle and select delegate
    func scrollViewDidScroll(scrollView: UIScrollView){
        if (scrollView.contentOffset.x != 0) {
            var offset = scrollView.contentOffset;
            offset.x = 0;
            scrollView.contentOffset = offset;
        }
    }



UICollectionView
implement protocols UICollectionViewDataSource,  UICollectionViewDelegate, ctrl drag from collection view data source and delegate to yellow circle with white rectangle
add a label and an image to the table view cell. Create a subclass of and set the class of hte cell to it.  change dell identifier and reusable identifier(e.g. PRODUCT_CVC)
class ProductCVC: UICollectionViewCell {
    @IBOutlet weak var productLabel: UILabel!
    @IBOutlet weak var productImage: UIImageView!
}

in viewdidload
productCV.delegate=self
productCV.dataSource=self
 
   func collectionView(collectionView: UICollectionView,
        numberOfItemsInSection section: Int) -> Int{
            return productArr.count
    }
   
   
    func collectionView(collectionView: UICollectionView,
        cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
            var cell = productCV.dequeueReusableCellWithReuseIdentifier("PRODUCT_CVC", forIndexPath: indexPath) as ProductCVC    //identifier of cell
           
            var p = productArr[indexPath.row]
            cell.productLabel.text = p.name
           
            return cell
    }



















Comments