xcode - Swift convert code to component for use multiple times -
i'm swift newbie , i'm trying achieve feels should easy lack of knowledge of storyboard + swift + terminology holding me back!
i'd create horizontal scroller component achieves following design goals:
- i can add view in app few lines of code
- i can pass in array of values configure each of elements in scroller
- the scroller elements (cells?) designed in .xib file
- i can have multiple instances of scroller in view
i've created simple example scroller has following structure:
- viewcontroller (horizontalscrollervc.swift)
- storyboard (used creating outlets, constraints , config)
- a uicollectionviewcell subclass (mycell.swift)
- a custom xib file class property set mycell.swift (mycell.xib)
i imagine component might used in viewcontroller's viewdidload() method this:
//**pseudo code** let data1 = ["a","b","c"] let data2 = ["1","2","3"] let scroller1:myscroller = scrollerfromdata(data:data1) scroller1.constraints = somepositioningconstraints view.add(scroller1) let scroller2:myscroller = scrollerfromdatawithcelltype(data:data2,celltype:"mycell2") scroller2.constraints = somedifferentpositioningconstraints view.add(scroller2)
any advice how can convert code/structure can use in way described above great.
code
horizontalscrollervc.swift
import uikit class horizontalscrollervc: uiviewcontroller { // set data let dataarray = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"] // create outlet communicate collectionview @iboutlet weak var mycollectionview: uicollectionview! override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. let cellnib = uinib(nibname: "mycell", bundle: nil) self.mycollectionview.registernib(cellnib, forcellwithreuseidentifier: "mycell") self.mycollectionview.backgroundcolor = uicolor.init(colorliteralred: 0.9, green: 0.6, blue: 0.9, alpha: 1.0) } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. } // mark: collectionview methods func collectionview(collectionview: uicollectionview, numberofitemsinsection section: int) -> int { return dataarray.count } func collectionview(collectionview: uicollectionview, cellforitematindexpath indexpath: nsindexpath) -> uicollectionviewcell { let cell = collectionview.dequeuereusablecellwithreuseidentifier("mycell", forindexpath: indexpath) as! mycell self.configurecell(cell, forindexpath: indexpath) return cell } func configurecell(cell: mycell, forindexpath indexpath: nsindexpath) { let celltitle = dataarray[indexpath.row] cell.celltitle.text = celltitle } }
mycell.swift
import uikit class mycell: uicollectionviewcell { @iboutlet weak var celltitle: uilabel! override func awakefromnib() { self.backgroundcolor = uicolor.init(colorliteralred: 0.95, green: 0.95, blue: 0.95, alpha: 1.0) self.celltitle.textcolor = uicolor.darkgraycolor() self.layer.cornerradius = 5 } }
the mycell.xib simple incase helps, here's xml:
<?xml version="1.0" encoding="utf-8" standalone="no"?> <document type="com.apple.interfacebuilder3.cocoatouch.xib" version="3.0" toolsversion="10117" systemversion="15f34" targetruntime="ios.cocoatouch" propertyaccesscontrol="none" useautolayout="yes" usetraitcollections="yes"> <dependencies> <deployment identifier="ios"/> <plugin identifier="com.apple.interfacebuilder.ibcocoatouchplugin" version="10085"/> <capability name="constraints layout margins" mintoolsversion="6.0"/> </dependencies> <objects> <placeholder placeholderidentifier="ibfilesowner" id="-1" userlabel="file's owner"/> <placeholder placeholderidentifier="ibfirstresponder" id="-2" customclass="uiresponder"/> <view contentmode="scaletofill" id="in0-l3-epb" customclass="mycell" custommodule="testola" custommoduleprovider="target"> <rect key="frame" x="0.0" y="0.0" width="210" height="140"/> <autoresizingmask key="autoresizingmask" widthsizable="yes" heightsizable="yes"/> <subviews> <label opaque="no" userinteractionenabled="no" contentmode="left" horizontalhuggingpriority="251" verticalhuggingpriority="251" text="label" textalignment="natural" linebreakmode="tailtruncation" numberoflines="4" baselineadjustment="alignbaselines" adjustsfontsizetofit="no" translatesautoresizingmaskintoconstraints="no" id="h9q-ha-znf"> <rect key="frame" x="8" y="8" width="118" height="64"/> <fontdescription key="fontdescription" type="system" pointsize="17"/> <color key="textcolor" red="0.0" green="0.0" blue="0.0" alpha="1" colorspace="calibratedrgb"/> <nil key="highlightedcolor"/> </label> </subviews> <color key="backgroundcolor" white="1" alpha="1" colorspace="custom" customcolorspace="calibratedwhite"/> <constraints> <constraint firstitem="h9q-ha-znf" firstattribute="trailing" seconditem="in0-l3-epb" secondattribute="trailingmargin" constant="-76" id="s2o-ee-cyh"/> <constraint firstattribute="bottommargin" seconditem="h9q-ha-znf" secondattribute="bottom" constant="60" id="u0s-fw-rfv"/> <constraint firstitem="h9q-ha-znf" firstattribute="leading" seconditem="in0-l3-epb" secondattribute="leadingmargin" id="rwe-wi-vff"/> <constraint firstitem="h9q-ha-znf" firstattribute="top" seconditem="in0-l3-epb" secondattribute="topmargin" id="sl1-pt-fj7"/> </constraints> <freeformsimulatedsizemetrics key="simulateddestinationmetrics"/> <connections> <outlet property="celltitle" destination="h9q-ha-znf" id="8e8-hl-bcx"/> </connections> <point key="canvaslocation" x="195" y="139"/> </view> </objects> </document>
here's storyboard xml
<?xml version="1.0" encoding="utf-8" standalone="no"?> <document type="com.apple.interfacebuilder3.cocoatouch.storyboard.xib" version="3.0" toolsversion="10117" systemversion="15f34" targetruntime="ios.cocoatouch" propertyaccesscontrol="none" useautolayout="yes" usetraitcollections="yes" initialviewcontroller="49e-tb-3d3"> <dependencies> <deployment identifier="ios"/> <plugin identifier="com.apple.interfacebuilder.ibcocoatouchplugin" version="10085"/> <capability name="constraints layout margins" mintoolsversion="6.0"/> </dependencies> <scenes> <!--first--> <scene sceneid="hnz-n2-bh7"> <objects> <viewcontroller id="9pv-a4-qxb" customclass="horizontalscrollervc" custommodule="testola" custommoduleprovider="target" scenememberid="viewcontroller"> <layoutguides> <viewcontrollerlayoutguide type="top" id="ia1-k6-d13"/> <viewcontrollerlayoutguide type="bottom" id="4ug-mw-9ay"/> </layoutguides> <view key="view" contentmode="scaletofill" id="tsr-hk-won"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <autoresizingmask key="autoresizingmask" widthsizable="yes" heightsizable="yes"/> <subviews> <collectionview clipssubviews="yes" multipletouchenabled="yes" contentmode="scaletofill" datamode="prototypes" translatesautoresizingmaskintoconstraints="no" id="zd4-s1-vkm"> <rect key="frame" x="-4" y="40" width="383" height="150"/> <constraints> <constraint firstattribute="height" constant="150" id="f2e-db-ecy"/> </constraints> <collectionviewflowlayout key="collectionviewlayout" scrolldirection="horizontal" minimumlinespacing="10" minimuminteritemspacing="10" id="ayp-cr-c33"> <size key="itemsize" width="210" height="140"/> <size key="headerreferencesize" width="0.0" height="0.0"/> <size key="footerreferencesize" width="0.0" height="0.0"/> <inset key="sectioninset" minx="10" miny="0.0" maxx="10" maxy="0.0"/> </collectionviewflowlayout> <cells> <collectionviewcell opaque="no" clipssubviews="yes" multipletouchenabled="yes" contentmode="center" id="zbw-co-lp9"> <rect key="frame" x="10" y="-20" width="210" height="140"/> <autoresizingmask key="autoresizingmask" flexiblemaxx="yes" flexiblemaxy="yes"/> <view key="contentview" opaque="no" clipssubviews="yes" multipletouchenabled="yes" contentmode="center"> <rect key="frame" x="0.0" y="0.0" width="210" height="140"/> <autoresizingmask key="autoresizingmask"/> <color key="backgroundcolor" white="0.0" alpha="0.0" colorspace="calibratedwhite"/> </view> <size key="customsize" width="210" height="140"/> </collectionviewcell> </cells> <connections> <outlet property="datasource" destination="9pv-a4-qxb" id="p0g-qn-oud"/> <outlet property="delegate" destination="9pv-a4-qxb" id="u7n-os-ldt"/> </connections> </collectionview> </subviews> <color key="backgroundcolor" white="1" alpha="1" colorspace="custom" customcolorspace="calibratedwhite"/> <constraints> <constraint firstitem="zd4-s1-vkm" firstattribute="top" seconditem="ia1-k6-d13" secondattribute="bottom" constant="20" id="0eh-uz-at3"/> <constraint firstattribute="trailingmargin" seconditem="zd4-s1-vkm" secondattribute="trailing" constant="-20" id="2wl-8r-h8o"/> <constraint firstitem="zd4-s1-vkm" firstattribute="leading" seconditem="tsr-hk-won" secondattribute="leadingmargin" constant="-20" id="xxf-oy-0bo"/> </constraints> </view> <tabbaritem key="tabbaritem" title="first" image="first" id="acw-dt-ckf"/> <simulatedscreenmetrics key="simulateddestinationmetrics" type="retina47"/> <connections> <outlet property="mycollectionview" destination="zd4-s1-vkm" id="xwz-uu-tsb"/> </connections> </viewcontroller> <placeholder placeholderidentifier="ibfirstresponder" id="w5j-7l-pyd" scenememberid="firstresponder"/> </objects> <point key="canvaslocation" x="749.5" y="-320.5"/> </scene> <!--second--> <scene sceneid="wg7-f3-orb"> <objects> <viewcontroller id="8rj-kc-sve" customclass="secondviewcontroller" custommodule="testola" custommoduleprovider="target" scenememberid="viewcontroller"> <layoutguides> <viewcontrollerlayoutguide type="top" id="l7p-hk-0sc"/> <viewcontrollerlayoutguide type="bottom" id="djb-ko-ywx"/> </layoutguides> <view key="view" contentmode="scaletofill" id="qs5-rx-yew"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <autoresizingmask key="autoresizingmask" widthsizable="yes" heightsizable="yes"/> <subviews> <label opaque="no" clipssubviews="yes" userinteractionenabled="no" contentmode="scaletofill" text="second view" textalignment="center" linebreakmode="tailtruncation" minimumfontsize="10" translatesautoresizingmaskintoconstraints="no" id="zeq-fu-wv5"> <rect key="frame" x="83" y="313" width="210" height="42"/> <color key="backgroundcolor" white="1" alpha="1" colorspace="calibratedwhite"/> <fontdescription key="fontdescription" name="helvetica" family="helvetica" pointsize="36"/> <color key="textcolor" red="0.0" green="0.0" blue="0.0" alpha="1" colorspace="calibratedrgb"/> <nil key="highlightedcolor"/> </label> <label opaque="no" clipssubviews="yes" userinteractionenabled="no" contentmode="left" horizontalhuggingpriority="251" verticalhuggingpriority="251" text="loaded secondviewcontroller" textalignment="center" linebreakmode="tailtruncation" baselineadjustment="alignbaselines" adjustsfontsizetofit="no" translatesautoresizingmaskintoconstraints="no" id="ndk-cv-gan"> <rect key="frame" x="81" y="363" width="215" height="17"/> <fontdescription key="fontdescription" type="system" pointsize="14"/> <color key="textcolor" red="0.0" green="0.0" blue="0.0" alpha="1" colorspace="calibratedrgb"/> <nil key="highlightedcolor"/> </label> </subviews> <color key="backgroundcolor" white="1" alpha="1" colorspace="custom" customcolorspace="calibratedwhite"/> <constraints> <constraint firstitem="ndk-cv-gan" firstattribute="top" seconditem="zeq-fu-wv5" secondattribute="bottom" constant="8" symbolic="yes" id="day-4n-vmt"/> <constraint firstitem="ndk-cv-gan" firstattribute="centerx" seconditem="zeq-fu-wv5" secondattribute="centerx" id="jgo-fn-dhn"/> <constraint firstattribute="centerx" seconditem="zeq-fu-wv5" secondattribute="centerx" id="qqm-ns-xev"/> <constraint firstattribute="centery" seconditem="zeq-fu-wv5" secondattribute="centery" id="qzy-ky-pld"/> </constraints> </view> <tabbaritem key="tabbaritem" title="second" image="second" id="cpa-gy-q4n"/> </viewcontroller> <placeholder placeholderidentifier="ibfirstresponder" id="4nw-l8-le0" scenememberid="firstresponder"/> </objects> <point key="canvaslocation" x="750" y="360"/> </scene> <!--tab bar controller--> <scene sceneid="yl2-sm-qop"> <objects> <tabbarcontroller id="49e-tb-3d3" scenememberid="viewcontroller"> <nil key="simulatedbottombarmetrics"/> <simulatedscreenmetrics key="simulateddestinationmetrics" type="retina47"/> <tabbar key="tabbar" contentmode="scaletofill" id="w28-zg-yxa"> <rect key="frame" x="0.0" y="975" width="768" height="49"/> <autoresizingmask key="autoresizingmask" widthsizable="yes" flexibleminy="yes"/> <color key="backgroundcolor" white="0.0" alpha="0.0" colorspace="calibratedwhite"/> </tabbar> <connections> <segue destination="9pv-a4-qxb" kind="relationship" relationship="viewcontrollers" id="u7y-xg-7ch"/> <segue destination="8rj-kc-sve" kind="relationship" relationship="viewcontrollers" id="lzu-1b-eka"/> </connections> </tabbarcontroller> <placeholder placeholderidentifier="ibfirstresponder" id="hub-vb-40b" scenememberid="firstresponder"/> </objects> <point key="canvaslocation" x="0.0" y="0.0"/> </scene> </scenes> <resources> <image name="first" width="30" height="30"/> <image name="second" width="30" height="30"/> </resources> </document>
i have made custom controls before. have done in past make subclass uiview. using ibdesignable can start writing code control , show in storyboard code. once done drag , drop uiview storyboard , change class custom class made. since ibdesignable annotated class able see on screen control , not plain uiview. once place custom control in storyboard, can use auto layout define other stuff such width of control , on.
you mention passing data view controller. have used on projects.
override func prepareforsegue(segue: uistoryboardsegue, sender: anyobject?) { if let feed = segue.destinationviewcontroller as? feedtableviewcontroller segue.identifier == "embedfeed" { feed.yourvariable = [1,2,3] } }
Comments
Post a Comment