4

I have an array of objects, and I want a button for each object in the array. Am I doing it correctly? The buttons are not showing up on 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 am using parse to retrieve objects a certain distance from a point, which is working.

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's 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
  • You need to call self.view.addSubview(button) to add the buttons the view Commented Dec 11, 2015 at 6:39
  • I updated my code, but it still does not work Commented Dec 11, 2015 at 6:44
  • 2
    You are taking viewWidth and viewHeight from button.superview but you haven't added the button to the view at that point. You can use self.view rather than button.superView Commented Dec 11, 2015 at 6:50
  • Still does not work. I don't think the for loop is being called. The print("called") is not even showing up in the console. Commented Dec 11, 2015 at 6:55

1 Answer 1

1

I've found problem in your code - findObjectsInBackgroundWithBlock is async function, and your location array loop is called before findObjectsInBackgroundWithBlock finishes. And since locationArray is empty at this point - for loop isn't called.

Try this, using this approach locationsSet is called only then, when all objects are received from server.

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's 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)
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

See updated answer, I replaced button.supeview to self.view

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.