Passed integer incorrect value

Hi All,

I'm new here and hoping someone can help.

Ive allocated a stackView of UIButtons via the '.enumerated().map' method.

Set the .addTarget method to pass in the enumerated index into a method. The index passed is only of 0,1,2 however the value retrieved in the method is extremely large which is clearly not right. Anyone come across this before?

Any help would be great. Please see my code. Thanks :)

private func setupStackView() {
        let padding: CGFloat = 4
        let buttons = ["Cancel", "Save", "Send"]
        let arrangedSubviews = buttons.enumerated().map { (index, button) -> UIButton in
            let button = UIButton(type: .system)
            button.setTitle(buttons[index], for: .normal)
            button.setTitleColor(#colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1), for: .normal)
            button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
            button.backgroundColor = .clear
            button.addTarget(self, action: #selector(handleActions(index:)), for: .touchUpInside)
            return button

        let stackView = UIStackView(arrangedSubviews: arrangedSubviews)
        stackView.axis = .horizontal
        stackView.distribution = .fillEqually
        stackView.spacing = padding
        stackView.anchor(top: nil, leading: leadingAnchor, bottom: bottomAnchor, trailing: trailingAnchor, padding: .init(top: 0, left: padding, bottom: padding, right: padding), size: .init(width: frame.width, height: 49 - padding))

    @objc func handleActions(index: Int) {

The argument of an Obj-C action callback is a pointer to the action's sender. Replace it with this:

@objc func handleActions(sender: UIButton) {

And you will see that it's really the button instance. You might set the tag on the UIButton to the index you're expecting.

More info: Target-Action

1 Like

Legend! Appreciate the response Karl