How to create a UIImageView in swift programatically in a separate function? -
i want programatically create image view in function. hold background of image view , logos - in other image views can function , wan't have same thing on each one.
i created blank swift file , put following in it:
import foundation import uikit func background() { var imageview : uiimageview imageview = uiimageview(frame:cgrectmake(10, 50, 100, 300)); imageview.image = uiimage(named:"image.jpg") self.view.addsubview(imageview) } the error got on self.view.addsubview(imageview) line. error message use of unresolved identifier 'self'. tried removing word self line said instead view.addsubview(imageview) use of unresolved identifier 'view'.
my question doing wrong?
thanks
edit:
so have changed now, correct?
import foundation import uikit
class myviewcontroller: uiviewcontroller { func background() { var imageview : uiimageview imageview = uiimageview(frame:cgrectmake(10, 50, 100, 300)); imageview.image = uiimage(named:"bg.png") self.view.addsubview(imageview) } } i no longer errors in part when calling function viewcontroller class error message use of unresolved identifier 'background'. should add calling in other document doing thisbackground()` in view did load function.
to call instance function in swift can 2 ways, 1 within instance function or creating instance of class , calling it.
from instance function:
class myviewcontroller: uiviewcontroller { override func viewdidload() { super.viewdidload() // called within instance function self.background() } func background() { var imageview : uiimageview imageview = uiimageview(frame:cgrectmake(10, 50, 100, 300)); imageview.image = uiimage(named:"bg.png") self.view.addsubview(imageview) } } or somewhere else in code can create instance , call background this:
func someotherfunction() { // create instance , call background var myview:myviewcontroller = myviewcontroller() myview.background() } i recommend learn difference between instance method vs class method , decide trying do: what difference between class , instance methods?
Comments
Post a Comment