ios - If I want to create one of three similar types of cells in cellForRowAtIndexPath, how do I set the "common" properties? -
ios - If I want to create one of three similar types of cells in cellForRowAtIndexPath, how do I set the "common" properties? -
say have 3 different cell types different, have few fields nowadays in three, come same superclass, say, animal.
but animals different, , that's 3 different types of cells come in. 1 maybe lovable pets has unique look, lizards, , 3rd birds.
i want nowadays right kind of cell depending on kind of animal i'm dealing with. check animal's type property, dequeue cell, set , homecoming it.
but things name , height, animals have , i'd set centrally without having within every animal check repeated code.
so using polymorphism declared instance of parent, create each subclass , set specific properties, set general ones.
var cell: animalcell allow animal = animals[indexpath.row] switch animal.type { case "cat", "dog": cell = tableview.dequeuereusablecellwithidentifier("petcell", forindexpath: indexpath) pettableviewcell case "lizard": cell = tableview.dequeuereusablecellwithidentifier("lizardcell", forindexpath: indexpath) lizardtableviewcell cell.scaleamount = 7 cell.spikes = true default: cell = tableview.dequeuereusablecellwithidentifier("birdcell", forindexpath: indexpath) birdtableviewcell cell.wings = true } cell.animalnamelabel.text = animal.name cell.animalheightlabel.text = animal.height cell.animalsound.text = animal.sound homecoming cell but error within case statements still thinks cells of type animalcell, after create them right kind. isn't working.
how accomplish this?
but error within case statements still thinks cells of type animalcell
that because compiler pays attending static type of cell, not run-time type. as look changes type of object assign cell, not alter static type of cell. static type set var cell: animalcell declaration; assignments cell not alter static type.
you can prepare making local variable of proper type, setting properties through variable, , assigning cell @ end:
switch animal.type { case "cat", "dog": allow catordog = tableview.dequeuereusablecellwithidentifier("petcell", forindexpath: indexpath) pettableviewcell cell = catordog case "lizard": allow lizard = tableview.dequeuereusablecellwithidentifier("lizardcell", forindexpath: indexpath) lizardtableviewcell lizard.scaleamount = 7 lizard.spikes = true cell = lizard default: allow bird = tableview.dequeuereusablecellwithidentifier("birdcell", forindexpath: indexpath) birdtableviewcell bird.wings = true cell = bird } ios cocoa-touch uitableview swift
Comments
Post a Comment