2

if function "Savedata" is called, I add new button into [UIbutton] and I add new element into array [[Double]]. I want, for every button on index [i] to display data in array [[Double]] on index [i]. How shall I do the loop?

 @IBAction func Savedata(_ sender: Any) {

    subjectsznamky.insert(arrayx, at: 0) //subjectsznamky is the [[Double]] array

var button : UIButton
            button = UIButton(type: .system) as UIButton
            button.frame = CGRect(x:5, y: 20, width: 100.0, height: 30)
            button.setTitle(ourname, for: .normal)
            self.view.addSubview(button)
            buttons.append(button)

   for i in buttons.indices {
                buttons[i].frame.origin.y += 30
                buttons[i].addTarget // here I need to create the function, that every button on index [i] displays data in subjectsznamky on index[i]


}

Thank you.

Toby V.
  • 425
  • 1
  • 6
  • 15
  • What do you mean by the button 'displaying data'? – Frankie Jan 20 '17 at 18:15
  • I mean to display the data in label in VC – Toby V. Jan 20 '17 at 18:43
  • Do you have to insert into the array at element 0? Can you just append? If you can just append, you could use the buttons' `tag` field to store the matching array index. When a button is tapped, look at the `sender` button's `tag` and reference into the array. – Graham Perks Jan 20 '17 at 18:47
  • I have answered here. [Array of checkboxes](https://stackoverflow.com/questions/50068413/array-of-uibuttons-in-swift-4/63566031#63566031) – Narasimha Nallamsetty Aug 24 '20 at 17:42

1 Answers1

4

This is likely not an ideal way to manage your views or display data in your application. You should consider a UITableView instead.

That being said...

Maybe you can try something like this, keeping track of your buttons and values in a dictionary instead of a separate array. You'd still need an array specifically for your buttons though if you're trying to preserve order.

var hashes = [UIButton : [Double]]()
var buttons = [UIButton]()

@IBAction func saveData(_ sender: Any) {

    var button = UIButton(type: .system)
    button.frame = CGRect(x:5, y: 20, width: 100.0, height: 30)
    button.setTitle(ourname, for: .normal)
    self.view.addSubview(button)
    buttons.append(button)

    hashes[button] = arrayx

    for button in buttons {
        button.frame.origin.y += 30
        button.addTarget(self, action: #selector(MyClass.disaplayData(_:)), for: .touchUpInside)
    }
}

func displayData(_sender: UIButton) {
    if let doubleArray = hashes[sender] {
        print(doubleArray)
    }
}
Frankie
  • 11,508
  • 5
  • 53
  • 60