Reputation: 109
I searched a lot but could not find an answer, I will be very grateful for your help! I need to take a string and pass it to another location, but I cannot figure out how to do it in my case
func addTagLabels() {
for tag in hashtags {
let button = UIButton(type: .system)
button.setTitle("#\(tag)", for: .normal)
button.addTarget(self, action: #selector(didTap), for: .touchUpInside)
button.frame.size.width = button.intrinsicContentSize.width + tagPadding
button.frame.size.height = tagHeight
containerView.addSubview(button)
tagLabels.append(button)
}
}
@objc func didTap() {
delegate?.didTap(tag: tag)
}
Upvotes: 0
Views: 48
Reputation: 18924
There are two ways.
Way 1
Assign array index to your button tag. And on did tap action get index and get data from the index.
Like this
func addTagLabels() {
for (index, tag) in hashtags.enumerated() {
let button = UIButton(type: .system)
button.tag = index //<--- Here assign index
// Other code
}
}
Retrieve data
@objc func didTap(_ sender: UIButton) {
let tagData = hashtags[sender.tag]
delegate?.didTap(tag: tagData)
}
Way 2
Create a custom UIButton subclass and pass the value. Like this
class CustomButton: UIButton {
var data: String = ""
}
func addTagLabels() {
for tag in hashtags {
let button = CustomButton()
button.setTitle("#\(tag)", for: .normal)
button.addTarget(self, action: #selector(didTap), for: .touchUpInside)
button.data = tag //<-- Here
// Other code
}
}
@objc func didTap(_ sender: UIButton) {
if let btn = sender as? CustomButton {
delegate?.didTap(tag: btn.data)
}
}
Upvotes: 2