ios calendar week view - carleton university › ~ldnel › recent_honours_projects › ios... ·...
TRANSCRIPT
2017
IOSCALENDARWEEKVIEW
EVANCOOPERDATE: DECEMBER15TH2017SUPERVISOR: LOUISD.NELDEPARTMENT: SCHOOLOFCOMPUTERSCIENCEORGANIZATION: CARLETONUNIVERSITYCOURSE: COMP4905–HONOURSPROJECT
I
ABSTRACT
MobileapplicationIntegratedDevelopmentEnvironments(IDEs)provideawiderangeofpre-
madelibrariesthataiddevelopersinbuildingapplicationsformobileplatforms.Xcode,Apple’s
IDEfordevelopingiOSapplicationsforiPhones,iPadsandmore,isnoexception.Their
extensiverepositoryofuserinterface(UI)elementsallowsdeveloperstofocusonthecore
functionalityoftheirapplication,ratherthanbuildinganinterfacefromscratch.Alternatively,
third-partysourcessuchasCocoaPods,hostevenmore(over37thousand)(CocoaPodsDev
Team,2017)open-sourcelibrariestoalleviatethelimitationsofXcode’sdefaultwidgets.
However,therelacksonelibrarythatcanbeveryusefultoawiderangeofapplications;the
calendarlibrarywithaweek-viewinterface.
Thisprojecthassuccessfullycreatedanoriginallibrary,writtencompletelyiniOS’native
language:Swift.It’sgraphicalandprogrammaticinterfacesmimicthatofanativelibrary
includedinXcode.Thehigh-leveldatasourceanddelegateprotocolsprovidesimplisticaccess
tothecomplexfunctionalityunderthehood.Modulardesignoffersawiderangeof
customizationandusagetothevaryingprotocols.Requireddatacanbeloadedsynchronously
orasynchronouslywithoutcomplexcode,andinterfaceelementscaneasilybechangedat
individuallevels.
1
ACKNOWLEDGEMENTS
SWIFTDATE
DateandTimeManagementisprovidedbytheSwiftDatelibrary.Availableathttp://www.swift-date.comCreatedbyDanieleMarguttiandlicensedunderMITLicense.SwiftDatewasusedtoalleviatetheoverheadrequiredtocreatesophisticateddateobjects.Theuseofthisdependencyistohaveconsistenttimeparametersforeventobject.
2
TABLEOFCONTENTS
ABSTRACT.............................................................................................................................................I
ACKNOWLEDGEMENTS.........................................................................................................................1
SWIFTDATE.................................................................................................................................................1
LISTOFFIGURES...................................................................................................................................3
MOTIVATION........................................................................................................................................4
METHODOLOGY...................................................................................................................................6
INTRODUCTION............................................................................................................................................6
UIINFINITESCROLLVIEW................................................................................................................................7
Description...........................................................................................................................................7
Scrolling...............................................................................................................................................9
AccesstoFeatures.............................................................................................................................10
AdditionalIssues&Solutions.............................................................................................................11
WEEKVIEW...............................................................................................................................................13
Description.........................................................................................................................................13
WeekViewEvents..............................................................................................................................16
Interactingwithcalendarevents.......................................................................................................19
Styling................................................................................................................................................22
Dependency-SwiftDate....................................................................................................................24
RESULTS.............................................................................................................................................26
LIMITATIONS..............................................................................................................................................26
EXAMPLEAPPLICATION................................................................................................................................27
CONCLUSION.............................................................................................................................................28
BIBLIOGRAPHY...................................................................................................................................29
3
LISTOFFIGURES
FIGURE1–CarletonUniversity’smobileapplication’s“WeeklySchedule”section......................5
FIGURE2–UIInfiniteScrollViewscrollingprocess..........................................................................9
FIGURE3-UIInfiniteScrollViewDataSoucedefinition..................................................................11
FIGURE4-WeekViewDataSourceprotocoldefinition.................................................................17
FIGURE5-Displayingcalendareventsthatoccuratthesametime...........................................18
FIGURE6-WeekViewDelegateprotocoldefinition.....................................................................19
FIGURE7–Interactingwithcalendarevents...............................................................................21
FIGURE8-WeekViewStylerprotocoldefinition..........................................................................23
FIGURE9-UsingSwiftDatewithWeekViewDataSource.............................................................24
4
MOTIVATION
Ifirstbecameawareoftheneedforthistypeoflibrarywhilebuildinganothermobile
applicationforaprojectduringmythirdyearofundergraduatestudies.Throughoutthe
semester,wewererequiredtobuildamobileapplicationtocompletion,onachosenplatform,
insmallgroupsofstudents.Schedula,ourapplication,hadamaingoaltoautomatethecourse
selectionprocessforCarletonUniversitystudentsbygeneratingallpermutationsofclass
schedulesthatwouldworkforeachstudentonanindividuallevel.Theideaforthisapplication
arosewhenmygroupandIwerereflectingontheamountofmanualeffortrequiredtoregister
forclassesthatwouldfitwellwithournon-academiclives,suchasworkandothertime
commitments.Whenbuildingaschedulewithourapplicationstudentshavetheabilitytoopt-
outofentiredaysofclasses.Theycanalsoindicateapreferenceformorning,afternoonor
eveningclasses,andeveninputspecificblocksoftimeduringanydaywheretheywouldn’tbe
availabletoattendclasses.
Afterdesigningandimplementingthesoftwaretoachievethesegoals,thenextstepwasto
presentittotheuser.Theviewthatdisplayedthedatatotheuserneededtohavetwoprimary
properties:concurrentlydisplayallfiveweekdaysatthesametime,andtheabilitytoseethe
differentclassesoccurringeachday,similartoCarletonUniversity’smobileapplicationthata
studentusestoviewtheclassestheyhavefortheweek[Fig.1].However,neitheriOSor
Androiddevelopmentenvironmentshavebuilt-inuser-interfacewidgetstodisplaydatainthis
manner.Afterextensiveresearch,athird-partylibraryforAndroidwasfoundonGitHub,that
satisfiedtheneedsoftheinterface.Thislibrary,calledAndroidWeekView,issophisticatedand
simplistic.ThisforcedtheapplicationtobedevelopedforAndroiddevices,andstillleftthe
domainofApple’siOSuntouchable.However,itallowedthedevelopmentcycleoftheclass
projecttofocusonthecorefunctionality,byalleviatingtheneedtodevelopanintricate
interfaceelementfromscratch.
Ayearlater,followingthecompletionoftheclassproject,iOSstilldidn’thaveanativeorthird-
partylibrarythatfulfilledtheneedsofmythird-yearcourseschedulingapplication,orofthose
whousedAndroidWeekViewintheirownapplications.IstartedtowonderifIcoulddevelop
5
myownweekviewinterfacemyself,butwasuncertainastowhyithadnotbeencreated
already.Mymainjustificationwasthatdevelopersthoughttheeffortrequiredwouldoutweigh
thebenefit,sinceSwifthasahistoryofdrasticallychanging,duetoitsopensourcelanguage
andthefactthatitisrelativelyyoungwhencomparedtotheotherpopularlanguagesused
today.Nonetheless,Swift’sreleasecyclehasbeenslowingdownoverthelastyear,asit
approachesitsendgamereleases,andtheimpactofthisreasoningisbecominglesssignificant
(Apple,2017).OtherrationalesincludedthatIhaveyettofindsomeoneelse’sversionofa
weekview,duetopoorsearchqueriesonmyside,incompleteSEO’sfromthedeveloper,and
eventhepuresizeanddiversityoftheinternet.However,Ididn’tbelievethistobethecase,as
thedifferenceincurrentsearchresultsandthosefromthepreviousyearwereminimal.The
ideathatIcoulddevelopmyownversionforiOSplatformsbecamefeasible.
FIGURE1–CarletonUniversity’smobileapplication’s“WeeklySchedule”section.
6
METHODOLOGY
INTRODUCTION
TheprimarypurposeofthisprojectwastodesignaniOSlibrarythatcanbeusedbydevelopers
withintheirmobileapplications,nomatterthecontextoftheirapplication/project.Moreover,
thissoftwareisnotmeanttobeusedbythegeneralconsumersofiOSproducts,andisnota
full-fledgedappitsself.Throughoutdevelopment,extracarewastakenintoplacetoensurea
modulardesignwithutmostcompatibility.Hence,thislibraryanditssingledependencyisalso
writtencompletelyinSwift.Notonlyisthisprojectwritteninasinglelanguage,italsoattempts
tomimicSwiftdesignguidelines,sothatitfeelsnativetothelanguageandenvironment.
IniOSdevelopment,therearetwoavailablelanguages,Objective-CandSwift.Although
Objective-Cisalanguagewithmorehistoryandexperiencedusers,therearemanyother
reasonstowhyApple’sSwiftlanguagewaschosenfordevelopment.Primarily,itisthenew
languageofchoicebyAppledevelopers,andisthemainlanguageusedinmoderniOS,macOS
andtvOSSoftwareDevelopmentKits(SDKs).Sinceitisbuilton-topofitspredecessorandtheC
programminglanguage,itinheritsmanyofObjective-C’sabilities,whileatthesametime
addingitsownadvantages.Readabilityinaprogramminglanguageiscrucial,especiallywhen
buildinglibrariesthatareopen-source.Sincethegoalofthisprojectistodevelopanopen-
sourceiOSlibrary,thesource-codeneedstobeeasilyreadabletothedeveloperswhomayuse
it,tostreamlineintegrationandminimizeerrors.NotonlyisitmorereadablethanObjective-C,
itsresemblancetootherprogramminglanguageslikeJavaScriptandPythonmakes
understandingeveneasiertotoday’sdevelopers.
Therearetwoprimaryanddistinctclassesthatdrivetheperformanceofthislibrary.Thefirstis
theUIInfiniteScrollViewclass,whichsubclassesandbuildsontopofSwift’sUIScrollViewclass.
Themaingoalofthisclassistoaddandhandlecertainscrollingabilitiesthatarenotpresentin
UIScrollView.Secondly,WeekViewistheclassthatismeanttobeusedbyusersofthislibrary.It
implementsUIInfiniteScrollViewandaddsanyfunctionalityrelatedtocalendars.
7
UIINFINITESCROLLVIEW
DESCRIPTION
ThefirststeptobuildingacomprehensiveUIlibrary,wastodevelopasub-systemincharge
handingsomecorelow-endfunctionalitythatwouldstayconsistentthroughoutanyandall
iterationsofaniOSCalendarWeekView.Primarily,thislibraryneededtodisplayalargesetof
viewswiththesamestructureknownassub-views,eachrepresentingasingleday.Additionally,
itwasnecessarythatthislayercouldhandlethescrollingfunctionality,andprovidethefluidity
ofanhorizontally-infinitespace,souserscanfreelyscrollbetweeneachday.Initially,Swift’s
UICollectionViewandUIScrollViewclasseswerepromisingcandidatestofillbothrequirements
ofthesub-system.Being“[A]nobjectthatmanagesanorderedcollectionofdataitemsand
presentsthemusingcustomizablelayouts”,theUICollectionViewalreadyhastheproper
structureandinterfacetobefilledwithaviewthatrepresentseachday(Apple,2017).
However,theUIScrollViewclassgivesmorefreedomintermsof“scrollingandzoomingofit’s
containedviews”(Apple,2017).Bothoftheseinterfacesquicklybecameattractiveoptionsas
theyhadbeendevelopedbyApplethemselves,andarerobustandsophisticatedlibraries.
However,theseviewslackedaspecificabilitythatdeemedtheminvaluabletotheproject:ona
horizontalplane,theywereonlyabletoextendtheplaneontherightside,andthuscreateda
left-handscrollbarrierandrenderedthemselvesuselessonthatside.Ultimately,thismeant
thatdevelopingacustominterfaceforthecorefunctionalitieswouldbenecessary.
Thecustominterfacethatsuccessfullyhandlestheunderlyingfunctionalitiesisknowninthis
projectastheUIInfiniteScrollViewclass.Aninstanceofthisclasshastwocoreabilities:
horizontallyorverticallyinfinitescrollinginbothdirectionsofthechosenscrollplane,and
provideshigherlevelclassesaSwift-styleinterfaceforcontinuouslyinitializingtheviewsthat
wouldhaveasimilarstructure.Tobeabletokeeptrackofthescrollingactivitiesofauser,
UIInfiniteScrollViewsubclassesUIScrollView,hencethesimilarityinnames.Apple’spre-built
libraryincludesvariousscrolllistenerfunctionsthatarecalledduringspecificevents.Totake
advantageofthispowerfulfunctionality,thisinterfaceoverridesacouplekeyfunctionsthat,
8
together,allowfortheconstanttrackingofscrollposition.Thisabilitywasfundamentalto
providinganexperienceofaninfinitelylongplane.
ThetablebelowdescribesthedifferentparameterswithintheUIInfiniteScrollViewclass.
Althoughmostoftheparameterswithintheclasshaveaprivateaccesslevel,understandingthe
importanceanduseofeachparameteriscriticaltobeingabletoproperlyusethislibrary.
ParameterName Type Descriptionviews [[UIView]] Anestedcollectionwhereeach
indexatthetoplevelisacollectionofviewsmeantforaspecificrow/columninthescrollview.
viewRangeStart Int Anintegerthatrepresentstheindexatwhichtostartloadingthecontentofeachrow/columnfrom“views”.
loadPageCount Int Anintegerrepresentingthenumberofpagesthatareactivewithinthescrollview.
viewSize CGSize Thesizeofeachrow/columninthescrollview.
spacerSize CGFloat Afloatrepresentingtheamountofspacingbetweeneachrow/column.
viewsInPageCount Int Anintegerrepresentingthenumberofrows/columnswithineachpage.
scrollDirection ScrollDirection Thedirectioninwhichthescrollviewscrolls.Eitherverticalorhorizontal.
isSnapEnabled Bool ABooleanthatindicatesifthescrollviewshouldsnaptheclosestrow/columntotheedgeafterauserhasscrolled.
weekView WeekView TheWeekViewinstancethatinitializesthisclass.
dataSource UIInfiniteScrollViewDataSource AnobjectthatimplementstheUIInfiniteScrollViewDataSourceprotocol.
9
SCROLLING
Infinitescrolling,eitherinthehorizontalorverticaldirections,quicklybecameoneofthemost
difficultchallengestoovercomeduringthecourseofthisproject.WhenusingXcode’spre-
packagedinterfacepackagesonahorizontalplane,infinitelyscrollingtotherightonlyrequired
extendingthewidthoftheplanebysomearbitrarysizethatallowedtheadditionofacouple
moreviews.Onthecontrary,infinitelyscrollingtotheleftwasnotassimplistic.Addingspaceto
theleadingedgeofaviewrequirestheentireviewtobere-initialized,andallofitscontentsto
bere-added.Thesameconceptsappliedtoverticalscrollingplanes,whereaddingcontentto
thebottomissimple,butnotfortopcontent.Analysingtheworkbeingdoneduringthis
processrevealedalinearrelationshipbetweenthere-initializationtimeoftheinterfaceandthe
amountoftimestheinterfacehasalreadybeenre-initialized.Thismeantthataddingasingle
leadingviewtothescrollingplanewouldadditionallyre-loadeveryviewthatexistedbeforeit.
SincealluserinterfaceactivitywithiniOSapplicationsmustexecuteonthedevice’smain
thread,handlinguserinteractionandinfinitescrollinginthismannerwouldquicklyleadtopoor
performance(Apple,2017).
FIGURE2–UIInfiniteScrollViewscrollingprocess
10
InordertoavoidalinearrelationshipinUIinitializationthatcouldfreezetheapplicationasa
whole,aconstantamountofreal-estateonthescrollplaneneededtobeloadedeachtime.The
solutionwastoonlyloadinviewsthatarerelativetothecurrentpositionofthescreen.These
viewsfilltheavailablespaceofavailableinthescrollplane,andthescreencanfreelyscroll
throughthem.Toprovidetheappearanceandexperienceofaninfinitelyscrollingview,
UIInfiniteScrollViewimplementsandusesthedelegatemethodsofSwift’sUIScrollViewtoact
onspecificuser-initiatedevents.Whenthevisiblecontentwithinthescrollviewisdetectedto
benearingeitheredgeoftheloadedcontent,theUIInfiniteScrollViewwillre-initializethe
contentallthecontentwithin,andre-positionthescreentothemiddleofthecontent.This
functionalitymakesitappearasthoughthereisnoendtothescrollview’scontent,sincethe
user’sscreenwillneverreachtheend,andtheywillnotfeelresistancewhenscrollingthe
screen[Fig.2].
ACCESSTOFEATURES
Forhigh-levelclassestoutilizethisframework,UIInfiniteScrollViewprovidesaneasytouse
interfaceintheformofaSwift-styleprotocol.Swiftprotocolsdefine“blueprint[s]ofmethods,
properties,andotherrequirementsthatsuitaparticulartaskorpieceoffunctionality”(Apple,
2017).Theadvantagetousingprotocolsisthatcertainfunctionalitiesandtasksforagivenclass
canbedelegatedtootherclasses,aslongastheyproperlyconformtotheprotocolinquestion.
InSwift,UIobjectsoftenhavetwoprimaryprotocols;thedata-sourceandthedelegate.
Objectsthatactasadata-sourcewilloftenprovidethedatathatwillpopulatetheclassthat
makesuseofthedata-source.Delegateobjectsoftenconformtotheobserverpattern(aterm
mademainstreambytheGangofFour)bybeingabletoreceiveeventsandactions,andthen
performoperationswhentriggeredbytheprimaryclass(Gamma,Helm,Johnson,&Vlissides,
1994).Inthecontextofthisproject,sincetheonlyeventsthatwillbetriggeredby
UIInfiniteScrollViewarerelatedtoscrolling,andtheywillalwaysbehandledthesame,onlya
singleprotocolhasbeenimplemented.UIInfiniteScrollViewDataSourceprotocol[Fig.3]defines
asinglemethodwiththetaskofcreatingeachroworcolumnasitsneeded,atruntime.The
11
protocolmethodiscalledsynchronouslyonthemainthread,withanadditionalcompletion
handlerforotherusagescenarios.Inordertoproperlytakeadvantageofthisprotocolmethod,
askeletonfortheroworcolumnshouldbeimmediatelyreturnedinsynchronousfashion,while
additionalcomponentsthateitherneedtoberetrievedfromtheinternetorsimplytakelonger
tocreateingeneralshouldbeaddedviathecompletionhandler,sonottodisruptthemain
thread.Itisimportanttonotethatobjectspassedtothecompletionhandlerwillbeaddedas
sub-viewstotheroworcolumnthatisbeingcreated.Forexample,incontextofaweek-view
calendar,thestaticstructureofthecalendar’sdayshouldbereturnedtotheprotocolmethod,
whileeventsforthedayshouldbepassedtothecompletionhandler.
FIGURE3-UIInfiniteScrollViewDataSoucedefinition.
ADDITIONALISSUES&SOLUTIONS
Theimprovedscroll-handlingmethod,althoughallowingforaconstantrelationshipinUI
initialization,hasatradeoffintermsofdatastorage.Giventhefactthatold,unusedsub-views
withinUIInfiniteScrollViewwillberemovedtomakewayforthenewones,theseviewsthatare
12
beingremovedmustbesavedtodisk,toallowforthemtobere-loadedwhentheuserscrolls
backtoitspositiononthescrollplane.Additionalproblemsalsoarose,includingsavingthese
viewstodiskusingadatastructurethatfacilitatedeasyretrievalofspecificelements,andre-
addingviewswithextremecoordinatesthatlieoutsideUIInfiniteScrollView’scontent-view
scope.
Despitethefactthatthisone-to-onerelationshipbetweendiskstorageandrowsorcolumns
createdhasemergedfromtheimprovedscrollmechanism,ithasfarlessofanegativeimpact
onperformancethantheoriginalscrollingsystem,asthesamedatathatisbeingsavedtodisk
wouldinsteadtobesavedtomemory.Inadditiontothemainthreadpotentiallybeinglocked,
storinglargeamountsofdatainsystemmemorywilleventuallybecomedetrimentaltothe
performanceofamobileapplicationandthedeviceitself.Thiswouldhaveoccuredespecially
quicklywhenworkingwithdatatypesthathavesignificantlylargesizes,suchasvideosor
images.Inordertore-loadthesesub-viewswhenthey’reneeded,acoupleadditionalsteps
wererequiredinordertoalleviatenewissuesthatarose.Firstly,thedatastructurethatsaved
alltheviewsneededtobearrangedinacertainwaythatwouldmakethemeasytoretrieve.
Theeasiestmethodwastosavetheviewsinanarray,andsortthearrayastheviewsappearon
screen;bytheirorigin’sxoryvalueasitwouldappearonaninfinitelylargeplane,depending
onwhetherUIInfiniteScrollViewscrollshorizontallyorvertically,respectably.Theprimaryissue
thatwasconsequenceofretrievingviewsfromdiskwasre-addingviewsthatextendedpastthe
contentviewofUIInfiniteScrollView.Forexample,viewsthatliveontheextremitiesofthe
scrollingplane,havecoordinatesthatareeithertoofarleftorrightofthecontentview,asit
hasalimitedwidth,withanoriginthatalwayshasxandyvaluesof0.Whentheseedge-views
wereaddedtothecontentviewofUIInfiniteScrollView,theywerenevervisibletotheuser
sincethescreenwouldconstantlyresetwhennearingtheedge,asdesignofthescroll
mechanism.
Combattingthisissueprovedtobemoredifficultasnewfeatureswereaddedtotheproject.It
wasevidentthattheviews’origincoordinateneededtobemodifiedsothatitwouldfitwithin
thescreen,however,themodificationofthecoordinatewouldremoveanyorderthatwas
13
alreadyestablishedinthearraythatheldtheseviews.Thesolutionwastomakeacopyofthe
viewthatshouldbeadded,andaddthenewinstancetoUIInfiniteScrollView.Thecoordinate
modificationprovedtobeasimpletask,sinceonlyoneofthexoryvaluesofthecopiedview
neededtobemodified,andtheotherwouldstayconstantatzero.However,whenacopyofa
viewwasmadealargerproblemarose.Whencopyingtheseviews,therewereoftenattributes
thatwerelostintheconversion,andsomecases,copyingsubclassesofSwift’snativeUIView
returnedanobjectoftheUIViewclassandnottheoriginalsubclass.Themostimportant
attributethatwasoftenlostwasthearrayofgesturerecognizers,whichmadeitimpossibleto
interactwithmostviewsthatwereaddedtoUIInfiniteScrollView.Thesolutionisatwo-step
process.First,anyUIViewsubclasspropertiesneededtobeexplicitlyencodedanddecodedby
implementingSwift’sencodefunctionanddecodinginitializer.Thesecondstepgoesagainst
object-orientedprogramming’spractices,byforcingthecopyoftheoriginalviewtobeaclass
ofthecreatedsubclass.Thisstepisnotgoodprogrammingpractice,asitbreaksabarrier
betweentheUIInfiniteScrollViewclass,andtheclassthatimplementsthedelegatebyhard-
codingandenforcingavariabletobeofacertainclass,whenthatclasslacksanyrelationship
withUIInfiniteScrollView.
WEEKVIEW
DESCRIPTION
Thefinalsteptowardscompletionofthisprojectwastodevelopacompleteinterfaceontopof
thecompletedfoundation.SincemanypartsarealreadybeinghandledinUIInfiniteScrollView,
theWeekViewclassonlyhadtofocusonspecificpropertiesandfunctionalitiesdirectlyrelated
tocalendars.Primarily,thisclassneededtocreatenewcalendareventsforeachdayand
displaythem.
InitializationofaWeekView,therearemanydifferentprocessesthattakeplace.Starting
initializationcanhappenindifferentwaysandcanbeachievedwithaverysmallsetofuser-
providedproperties,asinitializingfunctionsdefinedefaultvaluesforalmostallclass-attributes.
14
Ifaninstanceisbeingcreatedwithincode,onlytheframeofthecalendarandthecountofdays
thatareconcurrentlyvisiblearerequired.Alltheotherpropertieshavedefaultvaluesandcan
beoptionallypassedintotheinitializer.Storyboardinitializationiseveneasier,asthecalendar’s
frameisdefinedexplicitlywithinthelayoutfiles,andthevisibledayspropertytakesona
defaultvalueandcanbeoptionallymodifiedwithincodeafterestablishingaconnection
betweentheWeekViewinthestoryboardfilesasanoutletwithintherelevantviewcontroller.
Afterinitializationoftheprimarypropertiesthatwereeitherprovidedbydefaultortheuser,
thecalendarwillbuildaskeletonforitsowninterface.Mostimportantly,itwillcreatean
instanceofUIInfiniteScrollView,anddefineitsselfasthescrollview’sdelegatesinceit
conformstotheUIInfiniteScrollViewDataSourceprotocol.ThescrollviewwilldisplayalltheIt
willthenbuildthetimeview,whichisvisibleontheleftside.Thisviewdisplaysaselectedor
defaultrange(09:00to17:00)ofhoursduringtheday,whichisusedtoeasilydistinguishthe
timeatanypointwithinthecalendar.Lastly,atop-anchoredviewiscreatedwhichdisplaysthe
monthandyearofthecalendar.
ThetablebelowdescribesthedifferentparameterswithintheWeekViewclass.Althoughmost
oftheparameterswithintheclasshaveaprivateaccesslevel,understandingtheimportance
anduseofeachparameteriscriticaltobeingabletoproperlyusethislibrary.
ParameterName Type DescriptionmonthAndYearText UITextView Atextviewthatdisplaysthe
monthandtheyear.ItisatthetopoftheWeekView.
timeView UIView Aviewthatdisplayseachhouroftheday,orspecifiedtimeinterval.ItisontheleftoftheWeekView,undermonthAndYearText.
scrollView UIInfiniteScrollView Thescrollviewthatwilldisplayeachdayinthecalendar,alongwiththeeventsforthatday.ItistotherightoftimeViewandundermonthAndYearText.
15
events [WeekViewEvent] AcollectionofWeekViewEventsthatwerecreatedWeekViewDataSourceprotocol.
initDate DateInRegion TheinitialdatethattheWeekViewwillopenat.
visibleDays Int Theamountofdaysthatareconcurrentlyvisible.
startHour Int ThefirsthourofthedaytodisplaywithintheWeekView.
endHour Int ThelasthourofthedaytodisplaywithintheWeekView.
headerHeight CGFloat Theheightoftheheaderincludedineachday,displayinginformationsuchasthedayoftheweekanddayofthemonth.
respondsToInteraction Bool ABooleanvalueindicatingiftheWeekViewshouldrespondtouserinteractionwithindividualevents.
nowLineEnabled Bool ABooleanvalueindicatingiftheWeekViewshoulddisplayalineathecurrenttime.
colorTheme Theme AthemeusedforcoloringthecomponentsoftheWeekView.Eitherlightordark.
font UIFont ThefontusedthroughouttheWeekView.
nowLineColor UIColor ThecolorofalinethatdisplaysthecurrenttimeinWeekView
nowLine CAShapeLayer Thelineandthecirclethat,combined,displaythecurrenttimeinWeekView.nowCircle UIView
dataSource WeekViewDataSource TheobjectthatimplementstheWeekViewDataSourceprotocol.
delegate WeekViewDelegate TheobjectthatimplementstheWeekViewDelegateprotocol.
16
styler WeekViewStyler TheobjectthatimplementstheWeekViewStylerprotocol.
WEEKVIEWEVENTS
Displayingcalendareventsisthecoreobjectivetothisproject.Sincetheyaresofundamental
tothedesignandflowofthelibrary,thecreationoftheWeekViewEventclasswasnecessary.
Thisclassrepresentsacalendareventthatwouldbetypicallydisplayedinacalendar.Most
importantly,ithousesstartandendpropertiesthattogetherrepresentaspecificintervalin
timetowhichtheeventoccupies.Additionally,ittheeventhasatitlepropertythatismeantfor
aclearandconcisedescriptionofthemeaningoftheevent.Unimportanttoauserofthis
library,butfundamentaltointernallogic,WeekViewEventsself-initializeauniqueidentifier
(UUID)thateasilydistinguishesitsselffromallothercalendarevents.
AddingeventstothecalendarmakesuseofWeekView’sdatasourceprotocolmethod,
WeekViewDataSource[Fig.4].Conformingtothisprotocolisthemostimportantsteptousing
thislibrary,asitisthesingleaccesspointtopopulatingacalendarwithevents.Foreachday,
thisprotocol’sonlymethod,weekViewGenerateEvents,iscalledandexpectsacollectionof
eventsthatoccurduringthatday.Eachtimethattheprotocolmethodiscalled,itprovidesthe
implementingclasswiththedateofwhichtheeventsareexpectedtooccurwithin.Ina
calendar,itmakessensetoseparateeventsbythedaythattheyoccur,asmostonlylastfora
fewhoursaday,andrarelyspanacrossmultipledays.Unfortunately,duetothis
implementation,calendareventsthatdospanmultipledaysaresometimesincorrectly
representedtotheuserbyonlybeingvisibleinthefirstdaythattheyoccur.Awork-around
solutionforthisissueistoseparatetheeventtoaday-by-daybasis,andreturneachday
individuallytotheprotocolmethod.
17
FIGURE4-WeekViewDataSourceprotocoldefinition.
NotonlyistheWeekViewDataSourcethemostimportantprotocolforWeekView,italsohas
themostcomplexfunctionality.WhentheWeekViewneedstocalluponthedatasource
method,itwillstartanewbackgroundthreadtoretrievethecollectionofevents,meaningthat
weekViewGenerateEventsisactuallycalledasynchronously.Inadeveloper’sperspectivewho
wouldusethislibrary,thisimplementationallowsfortheireventstobefetchedsynchronously
orasynchronouslyfromtheinternet,withoutanyadditionaloverhead.InSwift,threadsare
startedandmanagedbytheDispatchQueueclass,whichissimplyapooloftasks.Tasksare
allocatedCPUtimebytheiOSdeviceitsself,basedonthetypeofoperationsthatwillbe
completed.Forexample,everyiOSapplicationhasahigh-priorityuserinterfacethread(UI)
who’smainpurposeistomakechangestothescreenthatausersees.FortheWeekView,each
taskaddedtothepoolisasinglecalltothedatasourceprotocolforasingleday.Thechallenge
thatoccurswhenworkingwiththreadsinanyprogramminglanguageandsystem,isthatthere
isnoguaranteeprovidedbythecomputerthatonethreadwillfinishbeforetheother.Solving
thisissue,andhavingtheabilityforout-of-orderexecutionisknownincomputerscienceas
18
concurrency.TheWeekViewisabletocomputeeventsconcurrentlybyexecutingcompletion
handlermethodonthemainthreadaftertheeventshavecompleted.Thecompletionhandler
usesthecollectionofgeneratedeventstocreatetheviewstorepresentthem,andsendthem
toitsUIInfiniteScrollView’sdatasourceprotocolcompletionhandlertobeadded.
Comparingcalendareventsisequallyimportantascreatingthem.Forexample,itisimportant
todeterminewhethertwocalendareventsoverlapwitheachother,sothattheycanbe
displayedproperly.Withouttheabilitytocomparethetimingofcalendarevents,usersmaynot
beabletoseeorinteractwithcertainevents,iftheyappeardirectlybehindanother.
ImplementingSwift’sComparableprotocol,bydefiningthe“less-than”and“equal-to”
operatorsallowsforsimplisticdeterminationonwhicheventoccursbeforeanother.By
comparingeventtimelinesagainsteachother,eventsthatoccuratthesametimecanbe
displayedproperly.Showingeventsthatoccuratthesametimerequirestheirwidthtobe
dividedproportionally,andtheirx-coordinatebemodifiedaccordingly[Fig.5].
FIGURE5-Displayingcalendareventsthatoccuratthesametime.
19
INTERACTINGWITHCALENDAREVENTS
Intoday’sdigitalworld,notonlyisitimportanttodisplaydata,buttointeractandmodifyitas
well.TheWeekViewDelegateprotocolallowsformorecomplexinteractionasidefromscrolling
throughdaysoftheweek.Allowinguserstointerfacewithcalendareventsistheprimary
functionoftheprotocol’sweekViewDidClickOnEventmethod,andallowsdeveloperstodefine
thenatureandbehaviouroftheinteraction.Byallowingitsselftohandleuserinteraction,
WeekViewcanreceiveatouch-gestureevent,determinethelocationandimpactofthetouch
andhandleitaccordingly.
FIGURE6-WeekViewDelegateprotocoldefinition.
20
AftertheWeekViewcallsonitsdelegatetoreceiveeachevent,itwillcallonitsstylerproperty
tocreatetheviewfortheevent.Wheneventsareinitialized,theyautomaticallyinitializea
constantuniqueidentifier(UID)propertythatisusedtoeasilydifferentiateitsselffromother
events.EventviewsaresubclassesofUIView,whicharenativeSwiftobjectsthatmanage
contentforaspecifiedrectangularareaonadevice’sscreen.ThesubclassofUIView,
WeekViewEventView,onlyaddsasingleproperty,whichisitsevent’sUID.Similartoanevent’s
UID,itisfundamentaltoidentifyingtheview’seventfromothereventsinthecalendar.With
theviewnowcreated,eitherthroughthedefaultorcustomimplementationofthe
WeekViewStyler,agesturerecognizerisaddedtotheview,sothatitcanhandleinteraction.In
Swift,gesturerecognizers"[decouple]thelogicforrecognizingasequenceoftouches(orother
input)andactingonthatrecognition”(Apple,2017).Eacheventview’sgesturerecognizerwill
callonaninternalfunctiontoWeekView,thathandlestheinteractionandsendsthe
informationtothedelegatethroughtheweekViewDidClickOnEventmethod.
21
Implementingthedelegatemethodisstraightforward,andrequiresminimaloverhead.Aclass
thatconformstheWeekViewDelegateprotocolwillsimplyneedtosetthedelegatepropertyof
theapp’sWeekViewinstancetoitsself,andimplementtheprotocolmethod.Itwillbenow
readytohandlegesturesactedonanycalendarevent,sincetheeventispassedthroughthe
delegate.Animplementationoftheprotocolcanincludeanythingfromprintingtheevent’s
detailstotheconsole,orpresentinganewviewtotheuserthatcanfocusonmoredetailed
informationrelatedtotheevent[Fig.7].
FIGURE7–Interactingwithcalendarevents
22
STYLING
Creatingaframeworkwiththeobjectiveforittobeusedbymanydifferentdevelopersand
projects,requirestheinterfacetobeadaptabletothestyleofthevariousapplicationsthat
wouldpossiblyuseit.Itisimportanttoprovidethisabilitytousersofthislibrary,asevery
applicationhasuniquestyle,andgenericlibrariesthatdiscouragecustomizationwillmostlikely
berejectedduringtheplanningphaseofanapplication.Inordertoachievethistypeof
functionality,aWeekViewimplementsaprotocolthathandlesvariousinterfacecomponents.
TheWeekViewStylerprotocol[Fig.8]containsafewdifferentandoptionalmethodsthatgive
animplementationtheabilitytochangeanyuserinterfacecomponent.Itallowsfordefinitions
oftheviewthatacalendareventisplacedin,thecolumnthataneventisplacedwhich
representsanindividualdayandthecolumn’sheaderthatbyconvention,displaysthedate.In
eachprotocolmethod,thereisarecurringparameterofacontainerthatisextremely
importanttotheusageofcustomstyling.Whenallowinguserstomodifytheviewcomponents
oftheWeekView,itbecameapparentthatsomeconstraintstothelevelofcustomizability
neededtobeadded.Eachcontainerprovidedtotheprotocolmethodsisthecontainerthatwill
hostthenewviewthatisbeingcreated.Thismeansthatviewsthatarereturnedtoany
WeekViewStylerprotocolmethodsneedtohavethesamedimensionsasthecontainerthat
wasprovidedduringtheirfunctioncall.Otherwise,theWeekViewwilluseitsown
implementationofthestylingmethodtodefinetherequiredview.Addingthisverificationstep
preventsanimplementationofWeekViewtobe
Bydefault,inSwift,allprotocolmethodsaremandatory.Thismeansthataclasswhich
conformstoaprotocolmustimplementallthemethodsthataredefinedintheprotocol.In
mostcases,thistypeofconformityisexpected,however,inthecontextofthisproject,a
developerwhoisaddingtheWeekViewtotheirapplicationmayonlywanttomodifyspecific
partsoftheview,andkeepthedefaultimplementationforothers.Byconsequence,thedefault
implementationneedstobedefinedintheWeekViewclasstocoverthecasewherenotall
protocolmethodsaredefinedbyagiveninstanceofWeekView.Duringinitializationofeach
customizableview,theWeekViewwillchecktoseeifit’s“styler”propertyrespondstothe
23
protocolmethodresponsibleforthecreationofthegivenview,andcalluponittoinitializethe
view.Inthecasewherethestylerdoesnotrespondthemethod,WeekViewwilluseitsown
implementationofthemethodandprovidethedefaultfunctionalityforviewcreation.Thisis
madepossiblebySwift’sresponds(to:)method,whichtestswhetherobjectsrespondtospecific
functioncalls,andultimatelyallowsdeveloperswhousethislibrarytomodifytheviewfreely
byimplementingonlytheprotocolmethodstheyrequire.
FIGURE8-WeekViewStylerprotocoldefinition.
24
DEPENDENCY-SWIFTDATE
Duringthecourseofdevelopment,itbecamedifficulttocreateandmanagesophisticateddate
objectswithSwift’snativeDatestructure.CreatingDateobjectsforspecifictimesrequiredodd
calculationssuchasthedifferenceintimebetweeninitializationofsuchanobject,andthe
actualdatethatwasattemptingtobecreated.Additionally,modifyingdatesinSwiftwaseven
moredifficulttoaccomplish,sinceitrequiredinitializationofhelperobjectsthatweredifficult
tounderstand.AfterattemptingtoworkwithSwift’sDatelibrary,Idecidedtouseapopular
third-partydatemanagementlibrarycalledSwiftDate.Itmadeinitializationandmodificationof
datesextremelyeasy,sincebothcouldbeaccomplishedinasinglelineofcode.Additionally,
SwiftDateisabletomanagedateobjectsacrossdifferenttime-zonesbydefault,providingan
addedbenefitthatwouldhaverequiredvaluableandsignificanttimeandefforttoachieve,if
Swift’snaturalDatelibrarywasused.
ThedocumentationprovidedwithSwiftDatewasalsoacontributingfactortoitbeingchosento
asthedatemanagementsystemsupportingthisproject.Itoutlinesindetailhowtocreateand
modifydateobjectsinaneasy-to-readfashion.Eachparameterandmethodareclearlyand
preciselyexplained,allowinganyuserofthislibrarytoquicklyunderstandhowtousethis
library.ThedocumentationalsoexplainshowAdditionally,theSwiftDatedocumentationeven
providesaconceptualoverviewthatdescribestheentireplatform,inordertoprovideageneral
understandingofitsabilities.
FIGURE9-UsingSwiftDatewithWeekViewDataSource
Ultimately,duetoSwiftDate’seaseofuse,documentationandpopularity,itwasaneasy
decisionforittobeincludedinthisprojectasareplacement.MostofSwiftDate’susewithin
25
thisprojectisinternal,andnotexposedtousers.However,withintheWeekViewDataSource
protocolmethod,calendareventsareexpectedtobereturned,witheachcalendarevent
expectingastartandenddate.Theimplementationofthisrequirementisstraightforwardand
canbeaccomplishedinminimallinesofcode[Fig.9].Ihaveconfidencethatdeveloperswho
areusingthislibraryintheirapplicationswillbeabletoquicklyandeasilyunderstandhowto
useSwiftDate.
26
RESULTS
LIMITATIONS
Althoughmuchhasbeenaccomplishedwiththisproject,therearesomelimitationstothe
featuresthatthelibraryprovides.
TheskeletonofthedisplayisgeneratedbytheUIInfiniteScrollViewclass,who’smainpurposeis
toallowforsimilarcontenttobescrollablethroughaninfinitetimeline,oneitherahorizontal
orverticalplane.Whilethisfunctionalityiscrucialtothefundamentalsofthecalendar’s
scrollingability,theimplementationhastheunfortunatelimitationofasingle-dimensional
scrollplane.Inthecontextofacalendar,thismeansthattheentirelengthofasingledaymust
bevisibleatalltimesontheuser’sscreen.Itmaybedifficultfordevicesthathavelimited
screenreal-estatetolegiblydisplayafulltwenty-fourhoursofpossiblecontentallatonce.
FixingthisissuewouldrequireUIInfiniteScrollViewtoallowforalimitedamountofscrolling,
oppositetheinfiniteplane.Unfortunately,thetimelimitationsofthisprojectprohibitedthe
abilitytoaddsuchfunctionality.
Respondingtointeractionwithcalendareventswasoneofthelastfeaturesthatwasaddedto
thecalendarview.Asexplainedpreviously,sincecertainpropertiesoftheUIViewclasssuchas
thecollectionofgesturerecognizerswouldbelostwhenacopyoftheviewwascreated,the
UIInfiniteScrollViewclasscouldnotbecompletelyindependentoftheWeekViewclass.More
specifically,theUIInfiniteScrollViewwouldhavetore-addthegesturerecognizersthatwere
lost.Thisrequiredtheexplicitre-initializationoftheseattributesandbyconsequence,forced
thescrollviewtochoosethetypeofrecognizerthatwasbeingaddedtotheviewsbeneathit.
Althoughinteractionisstillpossiblewiththecalendarevents,thedesignofthecomponents
onlyallowsforthelibrarytorespondtoonespecificgesture;atap.Inordertosolvethis
limitation,thescrollviewmechanismwouldneedtoavoidcopyingviewsandshouldusethe
originalinstancesprovidedbythedatasourceprotocol.
Althoughthislibraryaccomplishesitsprimarygoalofbeingabletodisplaycalendareventsina
weekview,ausefulfeaturewouldbetheabilitytochangethescopeoftheviewondemand.
27
Morespecifically,itwouldbeusefulifonecouldchangethenumberofdaysthatare
concurrentlyvisibleatruntime.Currently,aninstanceofWeekViewwillbeabletoonlyshowa
fixednumberofdaysatatime,andmakingachangetothatwouldrequirere-initializationof
theentireWeekView.Therearemanyconsequences,howeverthemostcriticalissuewouldbe
thefactthatallpreviouslycreatedcalendareventswouldneedtobeinitializedagain,making
thisissuemoreseverewheneventsareloadedfromtheinternet.Alongthesamelines,fully-
functionalcalendarapplicationshavemorethanjustaweekviewliketheoneprovidedinthis
library.Forexample,thedefaultiOScalendarapplicationcontainsamonthviewinwhichusers
gainanoverviewoftheentiremonth.Othercalendarapplications,suchasMicrosoft’sOutlook,
evenincludeoverviewsforanentireyear.Ultimately,thislibrarywouldbesignificantlymore
usefulandpowerfultousersiftheyhadtheabilitytoscalethescopeoftheircalendarfrom
theirchoosingwhilstkeepingtheirdataintact.
EXAMPLEAPPLICATION
Inthegitrepositorythathoststhesourcecodeforthisproject,thereisanincludedexample
iOSapplicationthatdemonstratestheabilitiesofthislibrary.Alongsidethedocumentation
providedina“readme”fileandwithinthecommentsofthecode,developerscanreferencethe
providedapplicationtogainabetterunderstandingoftheimplementationandusefulnessof
thisproject.
Thegoaloftheapplicationwasnottocreateafeature-heavyandcompleteapp,buttoonly
havethenecessarycomponentsrequiredtoshowcasethislibrary.Theapplicationhasasingle
viewcontrollerwithonlytwoproperties:aninstanceofWeekView,andasmalluser-interface
classusedforinteractionwithevents.
TheWeekViewinstanceisinitializedwithasmanydefaultvaluesaspossible,anddefinesthe
respondsToInteractionvaluetobetrue,allowingfortheviewcontrollertohandleinteractions
withthecalendarevents.Additionally,theviewcontrollerimplementsallthreeWeekView
protocols;WeekViewDataSource,WeekViewDelegateandWeekViewStyler.Itpopulateseach
28
daywithasingleeventthroughthedatasourceprotocol.Ithandleseventinteractionby
displayingadismissiblepopupoverthescreenwithinformationabouttheeventwiththe
EventDetailLauncherclass,whichisaisasimpleclassthatencapsulatestheabilitytodisplay
anddismissaminimalisticpopupviewovertheentirescreen.Finally,itimplementscustom
stylingbymodifyingonlytheeventviewwithacustomview.
CONCLUSION
Inall,thisprojecthasaccomplisheditsprimarygoals.SwiftWeekViewisanoriginaliOSlibrary
thathasalleviatedthemissingfunctionalityofApple’sdefaultcalendarapplicationthatis
shippedwithiOSdevices,bybeingabletodisplaycalendareventsinaweek-view.It’sdefault
implementationvisuallyresemblesotheriOSandmacOSapplications.Byprovidingpublic
protocolsashigh-levelinterfacestothecomplexfunctionality,alongsideprogrammaticand
storyboardinitializationoptions,thisinterfacecomponenthasanexperienceofanauthentic
Swiftinterfacelibrary.Aftercompletingthisproject,developingtheoriginalcoursescheduling
applicationthatmotivatedthecreationoftheWeekViewisnowsignificantlymorepossiblein
iOS.Iplantocontinuethedevelopmentofthisprojecttoaddadditionalfeaturesandeliminate
thelimitationsdescribedearlier.
29
BIBLIOGRAPHY
Apple.(2017,September19).CodeDiagnosticsDocumentation.RetrievedSeptember25,2017,
fromMainThreadChecker:
https://developer.apple.com/documentation/code_diagnostics/main_thread_checker
Apple.(2017,September19).SwiftDocumentation.RetrievedSeptember25,2017,from
Protocols:
https://developer.apple.com/libary/content/documentation/Swift/Conceptual/Swift_Pr
ogramming_Language/Protocols.html
Apple.(2017,September24).SwiftEvolution.RetrievedSeptember25,2017,fromApple
GitHub:https://apple.github.io/swift-evolution
Apple.(2017,September19).UICollectionView.RetrievedSeptember25,2017,fromUIKit
Documentation:https://developer.apple.com/documentation/uikit/uicollectionview
Apple.(2017,September19).UIGestureRecognizer.RetrievedSeptember25,2017,fromUIKit
Documentation:https://developer.apple.com/documentation/uikit/uigesturerecognizer
Apple.(2017,September19).UIScrollView.RetrievedSeptember25,2017,fromUIKit
Documentation:https://developer.apple.com/documentation/uikit/uiscrollview
CocoaPodsDevTeam.(2017,September16).CocoaPods.org.RetrievedSeptember15,2017,
fromCocoaPods.org:https://cocoapods.org/
Gamma,E.,Helm,R.,Johnson,R.,&Vlissides,J.(1994,November).DesignPatternsBook.
RetrievedfromGangofFour:http://wiki.c2.com/?DesignPatternsBook
malcommac.(2017,November26).SwiftDateMainConcepts.RetrievedfromSwiftDate:
https://malcomman.github.io/SwiftDate/main_concepts.html