Subclassing in Swift

S

Subclassing is a very simple and useful concept of inheritance, when we create a subclass of any existing class then that custom class inherits all the methods and properties of existing or predefined class and moreover we can add our own user defined properties and methods to it.

 

Here is the syntax with example for subclassing ,

class myCustomButton : UIButton

{

var section = Int()

}

Problem Statement :-

Consider the example of TableView and it consist Two Section and multiple rows in each section, every table cell has one UIButton and we want to get existing “Row” and “Section” for clicked UIButton.

 

Explanation:-

UIButton has property call “tag” , by setting  the “indexPath.row” we can get row  indexfor selected button but for getting section for selected button we can use above example of subclass.

Now change cellForRow datasource code as below.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

         let cell = demoTableView.dequeueReusableCell(withIdentifier: “cell”, for: indexPath) as!demoTableView

         cell.btn.tag = indexPath.row

         cell.btn.section = indexPath.section

         return playersCell

    }

 

Finally select button from table view and set “myCustomButton” as superclass to that button.

About the author

Shravankumar Gundawar

I am working as an iOS application developer at NanoStuffs Technologies Pvt. Ltd. since 9 months. I have total 2+ years of experience in this technology. Till date worked on more than 7 iOS applications, Includes the categories of shopping,Entertainment,Business etc.
Other than this, i love singing songs & proud to say that won many prizes for solo and duet singing competitions during school and college days.

By Shravankumar Gundawar

Category