ios8 - How to reference UILabel strong reference programmatically using Swift? -
using swift, have uilabel created programmatically in viewdidload override function:
var middledate = uilabel(frame: cgrect(x: (screenwidth / 2) - 45, y: 0, width: 90, height: 20)) middledate.text = "3:13:46 pm" middledate.font = uifont(name: "arialmt", size: 13) middledate.textalignment = .center
which works great.
then trying alter text in override function viewdidappear
. build failed message use of unresolved identifier 'middledate'
if utilize interface builder , drag , drop uilabel on view, give strong reference works great. there way reference programmatically created object strong reference?
or going incorrect?
this have on viewcontroller.swift:
i have feeling there much improve , cleaner way this.
override func viewdidload() { super.viewdidload() var middledate = uilabel(frame: cgrect(x: (screenwidth / 2) - 45, y: 0, width: 90, height: 20)) middledate.text = "3:13:46 pm" middledate.font = uifont(name: "arialmt", size: 13) middledate.textalignment = .center self.mytopview.addsubview(middledate) } override func viewdidappear(animated: bool) { super.viewdidappear(animated) var timer = nstimer.scheduledtimerwithtimeinterval(1.0, target: self, selector: selector("getlocaltime:"), userinfo: nil, repeats: true) allow mainloop = nsrunloop.mainrunloop() mainloop.addtimer(timer, formode: nsdefaultrunloopmode) func getlocaltime(timer: nstimer) { var todaysdate:nsdate = nsdate() var dateformatter:nsdateformatter = nsdateformatter() var centerdateformatter:nsdateformatter = nsdateformatter() dateformatter.dateformat = "h:mm:ss" var dateinformat:string = dateformatter.stringfromdate(todaysdate) middledate.text = "hello" } }
try this:
class viewcontroller: uiviewcontroller { var middledate = uilabel(frame: cgrect(x: (360 / 2) - 45, y: 200, width: 90, height: 20)) override func viewdidload() { super.viewdidload() middledate.text = "3:13:46 pm" middledate.font = uifont(name: "arialmt", size: 13) middledate.textalignment = .center self.view.addsubview(middledate) } override func viewdidappear(animated: bool) { super.viewdidappear(animated) middledate.text = "hello" } }
your issue middledate declared local scope within viewdidload function. in order class variable need declare @ class level. simplified class little create work me.
swift ios8 uilabel strong-references
No comments:
Post a Comment