Adding buttons for each object in the array

I have an array of objects and I want a button for each object in the array. Am I doing it right? Buttons do not appear in the view, and I don't think the for loop is being called. I want the buttons to be in a random position, different for each button. What am I doing wrong? I use parse to retrieve objects at some distance from the point that works.

var locationarray = [AnyObject]()
var userbutton = [UIButton]()

  override func viewWillAppear(animated: Bool) {
    let userlocation = PFUser.query()
    PFGeoPoint.geoPointForCurrentLocationInBackground(){
        (point:PFGeoPoint?, error:NSError?) -> Void in
        NSLog("Test log 1") // Never printed

        if point != nil {
            // Succeeding in getting current location
            NSLog("Got current location successfully") // never printed
            PFUser.currentUser()!.setValue(point, forKey: "userlocation")
            PFUser.currentUser()!.saveInBackground()
        } else {
            // Failed to get location
            NSLog("Failed to get current location") // never printed
        }

        var query = PFUser.query()
        query?.whereKey("userlocation", nearGeoPoint: point!, withinMiles: 2.0)
        query?.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]?, error: NSError?) -> Void in
            if(error == nil){
                for object in objects! {
                  self.locationarray.append(object)
                  print(self.locationarray)  
                }   
            }else{
                print(error)
            }
        })
    }

    for users in locationarray{
        let button = UIButton()
        button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
        button.frame = CGRectMake(100, 100, 100, 50)

        let buttonWidth = button.frame.width
        let buttonHeight = button.frame.height

        // Find the width and height of the enclosing view
        let viewWidth = button.superview!.bounds.width
        let viewHeight = button.superview!.bounds.height


        let xwidth = viewWidth - buttonWidth
        let yheight = viewHeight - buttonHeight

        // Generate a random x and y offset
        let xoffset = CGFloat(arc4random_uniform(UInt32(xwidth)))
        let yoffset = CGFloat(arc4random_uniform(UInt32(yheight)))

        // Offset the button center by the random offsets.
        button.center.x = xoffset + buttonWidth / 2
        button.center.y = yoffset + buttonHeight / 2

        self.userbutton.append(button)
        print("called")
        print(self.userbutton)
        self.view.addSubview(button)
    }
}
+4
source share
1 answer

I found a problem in your code - it findObjectsInBackgroundWithBlockis an asynchronous function, and the loop of your address array is called until completion findObjectsInBackgroundWithBlock. And since it is locationArrayempty at this point, the loop is not called.

, locationsSet , .

override func viewWillAppear(animated: Bool) {
  let userlocation = PFUser.query()
  PFGeoPoint.geoPointForCurrentLocationInBackground(){
    (point:PFGeoPoint?, error:NSError?) -> Void in
    NSLog("Test log 1") // Never printed

    if point != nil {
      // Succeeding in getting current location
      NSLog("Got current location successfully") // never printed
      PFUser.currentUser()!.setValue(point, forKey: "userlocation")
      PFUser.currentUser()!.saveInBackground()
    }else{
      // Failed to get location
      NSLog("Failed to get current location") // never printed
    }

    var query = PFUser.query()
    query?.whereKey("userlocation", nearGeoPoint: point!, withinMiles: 2.0)
    query?.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]?, error: NSError?) -> Void in
      if(error == nil){
        for object in objects! {
          self.locationarray.append(object)
          print(self.locationarray)
        }

        self.locationsSet()

       }else{
         print(error)
       }
    })
  }
}

func locationsSet(){
  for users in locationarray{
    let button = UIButton()
    button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
    button.frame = CGRectMake(100, 100, 100, 50)

    let buttonWidth = button.frame.width
    let buttonHeight = button.frame.height

    // Find the width and height of the enclosing view
    let viewWidth = self.view.bounds.width
    let viewHeight = self.view.bounds.height


    let xwidth = viewWidth - buttonWidth
    let yheight = viewHeight - buttonHeight

    // Generate a random x and y offset
    let xoffset = CGFloat(arc4random_uniform(UInt32(xwidth)))
    let yoffset = CGFloat(arc4random_uniform(UInt32(yheight)))

    // Offset the button center by the random offsets.
    button.center.x = xoffset + buttonWidth / 2
    button.center.y = yoffset + buttonHeight / 2

    self.userbutton.append(button)
    print("called")
    print(self.userbutton)
    self.view.addSubview(button)
   }
}
+1

Source: https://habr.com/ru/post/1619445/


All Articles