func makeAButton(){
var tag = 1
for post in postArray {
let cgX = CGFloat(post.x!)
let cgY = CGFloat(post.y!)
let button : DragImg = DragImg(frame: CGRect(x: cgX, y: cgY, width: 100, height: 100))
button.backgroundColor = UIColor.blueColor()
button.setTitle(post.user, forState: .Normal)
button.addTarget(self, action: #selector(self.buttonAction), forControlEvents: .TouchUpInside)
button.tag = tag
self.view.addSubview(button)
print(tag)
tag += 1
}
}
我目前在我的帖子阵列中有7件事,当我打印出标签时,我得到了
1 2 3 ......等等,最多7个。
但是发生的事情是,在aray的第0个项目中,正在创建1个按钮。然后在第一个,在那个x / y处创建了2个,并且它一直向上和向上,直到我在另一个上方获得7个按钮。
为什么会这样?我在这里想到for循环会说:
对于PostArray中的每个帖子,使用PostArray中该项目的数据制作一个按钮。
我如何将其更改为按预期工作?
编辑:(只发布我已经收到的所有内容)
import UIKit
import Firebase
class testController: UIViewController {
@IBOutlet weak var button : UIButton!
@IBOutlet weak var textField: UITextField!
var colorsArray = [String]()
var currentX = CGFloat()
var currentY = CGFloat()
var postArray = [CirclePost]()
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let position :CGPoint = touch.locationInView(view)
currentY = position.y
currentX = position.x
}
}
override func viewDidLoad() {
super.viewDidLoad()
DataService.ds.REF_BASE.child("Colors").observeEventType(.Value) { (snapshot: FIRDataSnapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
self.postArray = []
for snap in snapshots {
if let x = snap.value!["x"] as? CGFloat, y = snap.value!["y"] as? CGFloat, color = snap.value!["color"] as? String {
let post = CirclePost(postKey: snap.key, user: color , x: x, y: y)
self.postArray.append(post)
print(self.postArray.count)
self.makeAButton()
}
}
}
}
}
func makeAButton(){
var tag = 1
for post in postArray {
let cgX = CGFloat(post.x!)
let cgY = CGFloat(post.y!)
// let button = DragImg()
let button : DragImg = DragImg(frame: CGRect(x: cgX, y: cgY, width: 100, height: 100))
button.backgroundColor = UIColor.blueColor()
button.setTitle(post.user, forState: .Normal)
button.addTarget(self, action: #selector(self.buttonAction), forControlEvents: .TouchUpInside)
button.tag = tag
self.view.addSubview(button)
tag += 1
}
}
func buttonAction(sender: UIButton!) {
let button = postArray[sender.tag - 1]
print(button.user)
print("Button tapped")
}
@IBAction func buttonPressed(sender: AnyObject) {
let ref = DataService.ds.REF_BASE.child("Colors").childByAutoId()
ref.child("color").setValue(textField.text)
ref.child("x").setValue(currentX)
ref.child("y").setValue(currentY)
}
}
答案 0 :(得分:2)
这是你的问题:
for snap in snapshots {
...
self.postArray.append(post)
print(self.postArray.count)
self.makeAButton()
您正在向数组添加帖子,然后绘制数组(1个项目)。然后,下次添加其他帖子,然后绘制数组(2个项目),依此类推。
您需要将调用self.makeAButton()
移出for for循环。