Subclassing in Swift

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.



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.

Need more help?

Hi there, was your problem or query resolved? If not & need more assistance, please do reach out to us at, we'll be more than delighted to help. Nanostuffs has 7+ years of extensive Salesforce & iOS/Android experience.
Holler Box