Vijesh Kk Vijesh Kk - 11 months ago 49
iOS Question

UIView class getting called in the end of the loop

I am new to swift programming and was testing some scenarios.

I have a UIView class which I am using for drawing something. I will be adding this UIView class as a subview to my main viewcontroller multiple times using a for loop.

I have an entity in coredata which stores the configuration information of the Drawing which I do using the UIVIew class. Each entry will have details like ID, Diamension and some other details required for drawing.

After fetching the data from coredata, I am using a 'for' loop to iterate through each entries and then draw (UIView class as subview) using the data retrieved from coredata.

Each iteration of the loop need to create new subview using UIView class with dimensions and other details retrieved from the coredata. But I noticed that it loops through all entries and calls UIView class in the end of the loop even though .addsubView is in the middle of loop.

I can see it creates the same number of subviews as the core data entries, but since the view is getting called in the end of the loop, all subviews are getting created with the details of last entry core data.

My code is some thing like this. Please help me on this. thanks.

Main view controller.

let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
do {
let request = NSFetchRequest(entityName: "Projects")
let results = try context.executeFetchRequest(request)
if results.count > 0 {
GlobalVariable.sharedManager.starty = 50
for item in results as! [NSManagedObject]{
let titleout = String(item.valueForKey("title")!)
let startxp1 = item.valueForKey("startx")
let startxp2 = item.valueForKey("starty")
let projtag = item.valueForKey("pid")

GlobalVariable.sharedManager.title = titleout
let DrawLanes = DrawProj(frame: CGRect(x: startx, y: starty, width: 500, height: 200))
DrawLanes.backgroundColor = UIColor.clearColor()
DrawLanes.userInteractionEnabled = true
DrawLanes.tag = projtag

}catch {
print ("there was an error in fetch")


override func drawRect(rect: CGRect) {

let button = UIButton(type: .System) // let preferred over var here
button.frame = CGRectMake(24, 15, 300, 20)
button.backgroundColor = UIColor.orangeColor()
button.userInteractionEnabled = false
button.text = GlobalVariable.sharedManager.title


Answer Source

I think the point of failure is GlobalVariable.sharedManager.title = titleout and instantiating the view doesnot mean its drawRect will be called.

My solution would be making a new variable in DrawLanes and initializing variable with the titleout

DrawLines.buttonTitle = titleout

and in the drawRect put

button.title = self.buttonTitle