为什么数组中的最后一个对象出现了?

时间:2015-12-13 08:49:57

标签: ios swift

我正在尝试跨视图传递信息,这有效,但该程序没有获取正确的信息。我有一个数组中的按钮,在这种情况下是3个按钮,当我点击该按钮时,我想要按钮信息,即图像被转移到下一个视图。问题是无论我点击哪个按钮,数组的最后一个按钮都会将其数据传输到下一个视图。我该如何解决?

enter image description here

  var userbutton = [UIButton]()

   var userbutton = UIButton()
        userbutton.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
        userbutton.frame = CGRectMake(100, 100, 50, 50)
        userbutton.layer.cornerRadius = userbutton.frame.size.width/2
        userbutton.clipsToBounds = true
        userbutton.setImage(users, forState: .Normal)


 func buttonAction(sender: UIButton){

    for (index, users) in upimage.enumerate(){
    self.dicSelected = ["text" : usernamearray[index] , "image" :  upimage[index]]
    print(dicSelected)

    self.selectedData.text = usernamearray[index] as? String
    self.selectedData.image = upimage[index] as? UIImage

    self.performSegueWithIdentifier("nearmeprofile", sender: self)
    }
}
 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "nearmeprofile"){              
        let nextViewOBJ = segue.destinationViewController as! NearMeProfile
        nextViewOBJ.neardataModel = self.selectedData;
    }
}

2 个答案:

答案 0 :(得分:1)

如果要在单击按钮1时发送图像/文本1 ...单击按钮3时图像/文本3比最简单的方法是将标签分配给按钮并将所有这些标记连接到相同的操作。

例如,将标签100分配给第一个按钮,101分配给第二个按钮,将102分配给第三个按钮。我不想从0开始,因为默认情况下所有UI元素都有一个标记0。然后将所有按钮连接到操作

func buttonAction(sender: UIButton) {

   let index = sender.tag - 100 // remove the offset of 100    
   self.dicSelected = ["text" : usernamearray[index] , "image" :  upimage[index]]
   print(dicSelected)

   self.selectedData.text = usernamearray[index] as? String
   self.selectedData.image = upimage[index] as? UIImage

  self.performSegueWithIdentifier("nearmeprofile", sender: self)
}

答案 1 :(得分:1)

你用不同的方法问了同样的问题。但答案是一样的..

var userbutton = [UIButton]()
var upimage = [UIImage]()
var usernamearray = [String]()

for (index, users) in upimage.enumerate(){

        var userbutton = UIButton()
        userbutton.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
        userbutton.frame = CGRectMake(100, 100, 50, 50)
        userbutton.layer.cornerRadius = userbutton.frame.size.width/2
        userbutton.clipsToBounds = true
        userbutton.setImage(users, forState: .Normal)
        userbutton.tag = index  // <-- ADD this Line in your code.
}

func buttonAction(sender: UIButton) {
   let index = sender.tag
      self.dicSelected = ["text" : usernamearray[index] , "image" :  upimage[index]]

   print("index\(index)")

    self.selectedData.text = usernamearray[index] as? String
    self.selectedData.image = upimage[index] as? UIImage

    self.performSegueWithIdentifier("nearmeprofile", sender: dicSelected)

}