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)
}
}
self.view.addSubview(button)to add the buttons the viewviewWidthandviewHeightfrombutton.superviewbut you haven't added the button to the view at that point. You can useself.viewrather thanbutton.superViewprint("called")is not even showing up in the console.