Вы находитесь на странице: 1из 15

Interfaces and Code Binding

Delegate and DataSource Mr. Ahmed Qazzaz

last update Nov. 15th., 2019


1
Protocols

✤ Protocols are a method tp share functions between


different type of classes, each class should implement
these functions internally

✤ So the protocols contains only headers of the function

2
Protocol

protocol ProtocolName {
func firstFunctionName(parameters)->returnType
func secondFunction …. etc.
}

3
Protocol

4
Example
OBJAttributeProtocol

Class Shape UIImage

Class Circle Class Rectangle Class Image


Circle and Rectangle are both sub classes of shape
Image is sub class of UIImage (which is a native class)
But both circle and rectangle has shared function between them and
the image class, so they have a common protocol which is
OBJAttributeProtocol 5
Example Code

UIImage

6
ExampleUsage

✤ if you have a function that needs to get the attributes


of an object but you don’t know if you are going to
pass Shape or Image to this function it would be better
to pass a protocol that both are implements.

7
Delegate and DataSource

✤ Delegate and datasource are both protocols defined in


several objects in swift

✤ We use them to pass data, and notify objects with


different superclasses, as we mentioned before to
make shared functions between different classes

8
DataSource

✤ One of the most known data source protocols is the


one used to fill the table view (UITableView)

function call
Object of Type X
UITableView
UITableViewDataSource

9
UITableViewDataSource

✤ The tableView will call a function called “number of


rows in section” from its data source, the object that
implements datasource should implement this
function and return the number of rows to the table
view, this way the table view will know how many
rows should be presented in the list.

10
Setting TableView dataSource

✤ The tableView class contains a variable called


“dataSource” of the type “UITableViewDataSource”
which is a protocol, any class can implement it and
become qualified to be a datasource for a table view

✤ We will make our view controller implements the


UITableViewDataSource protocol

11
Setting TableView dataSource

✤ Select the table view

✤ Go to connections
inspector

✤ drag a connection
from the data source
outlet to the view
controller
12
Setting TableView dataSource

✤ The view controller should implement this protocol

UITableViewDataSource

UIViewController

Data Source
ViewController
TableView

13
Implement functions

✤ In UITableViewDataSource there is a required


functions should be implemented

✤ number of rows : returns the number of rows to be


presented

✤ cell for row at indexPath : Define the cell to be


presented

14
Watch and Learn

✤ Watch this video to learn more about TableViews.

✤ https://youtu.be/DThwGAp0BSI

✤ Do Not Publish This link

15

Вам также может понравиться