【问题标题】:Adding buttons for each object in array为数组中的每个对象添加按钮
【发布时间】:2015-12-11 06:34:25
【问题描述】:

我有一个对象数组,我希望数组中的每个对象都有一个按钮。我做得对吗?按钮没有显示在视图上,我认为没有调用 for 循环。我希望按钮处于随机位置,每个按钮都不同。我究竟做错了什么?我正在使用解析来检索距某个点一定距离的对象,这是有效的。

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) 将按钮添加到视图中
  • 我更新了我的代码,但还是不行
  • 您正在从button.superview 获取viewWidthviewHeight,但此时您尚未将按钮添加到视图中。您可以使用self.view 而不是button.superView
  • 还是不行。我认为没有调用 for 循环。 print("called") 甚至没有出现在控制台中。

标签: ios swift parse-platform


【解决方案1】:

我在您的代码中发现了问题 - findObjectsInBackgroundWithBlock 是异步函数,并且您的位置数组循环在 findObjectsInBackgroundWithBlock 完成之前被调用。由于此时 locationArray 为空 - 不会调用 for 循环。

试试这个,使用这种方法 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'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)
   }
}

【讨论】:

  • 查看更新的答案,我将 button.supeview 替换为 self.view