Swift sender.setTitle code didn't visible? - ios

I have question about sender title. I have a button and I want to change title according to some condition. In this point I made sender.setTitle() code but title appear only like 0.5 second. Its not visible let me say more clear. How can I solve it?
Here my code:
#objc func handleExpandCloseForAlim(sender: UIButton) {
if (sender.tag == 1) {
if keys[0] == 0 {
sender.setTitle("titlesample", for: .normal)
keys[0] = 1
}else{
keys[0] = 0
sender.setTitle("titlesampleclose", for: .normal)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
Here my header view code:
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 100))
// code for adding centered title
headerView.backgroundColor = .lightGray
let headerLabel = UILabel(frame: CGRect(x: 0, y: 10, width: tableView.bounds.size.width, height: 28))
headerLabel.textColor = UIColor.black
headerLabel.text = " Teslim Alınacağı Adres"
headerLabel.font = UIFont.boldSystemFont(ofSize: 14)
headerLabel.textAlignment = .left
headerView.addSubview(headerLabel)
// code for adding button to right corner of section header
let button: UIButton = UIButton(frame: CGRect(x:headerView.frame.size.width - 100, y:8, width:100, height:28))
button.setTitleColor(.black, for: .normal)
button.titleLabel!.font = UIFont.boldSystemFont(ofSize: 14)
button.layer.cornerRadius = 4
button.tag = 1
button.backgroundColor = UIColor.blue
button.addTarget(self, action: #selector(handleExpandCloseForAlim(sender:)), for: .touchUpInside)
headerView.addSubview(button)
return headerView

The problematic part in the code above is that you are reloading your tableview in the handleExpandCloseForAlim. Since your tableView is reloaded, it will invoke viewForHeaderInSection function in your tableView from where you are returning a headerView with no title. That's why your label is getting disappeared.
You can solve this by having your button label as a field in your viewcontroller may be. Sample code may be like the one follows.
class YourViewController: UITableViewController {
var buttonLabel: String = "titlesampleclose"
.......
}
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 100))
// code for adding centered title
headerView.backgroundColor = .lightGray
.........
.........
button.setTitle(buttonLabel,for: .normal)
button.addTarget(self, action: #selector(handleExpandCloseForAlim(sender:)), for: .touchUpInside)
headerView.addSubview(button)
return headerView
#objc func handleExpandCloseForAlim(sender: UIButton) {
if (sender.tag == 1) {
if keys[0] == 0 {
self.buttonLabel = "titlesample"
keys[0] = 1
}else{
keys[0] = 0
self.buttonLabel = "titlesampleclose"
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
Hope it helps.

Related

how to send a text with a send button to text field on swift iOS

I really new. all I want to do is send in the text I got on the password field as a secure text to the text field if that's possible. kind of like sending a text but with the secure text. the secure button just lets you see what is inside. I got that to work but I don't know how to transfer the information from one place to the other. do I create a function? Im sorry im a complete noob.
import UIKit
class ViewController: UIViewController {
private let scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.clipsToBounds = true
return scrollView
}()
private let secureButton : UIButton = {
let button = UIButton()
button.setTitle("Secure", for: .normal)
button.backgroundColor = .link
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 12
button.titleLabel?.font = .systemFont(ofSize: 20, weight: .bold)
button.layer.masksToBounds = true
button.addTarget( self, action: #selector(securebuttonTapped), for: .touchUpInside)
return button
}()
let sendButton : UIButton = {
let button = UIButton()
button.setTitle("Send", for: .normal)
button.backgroundColor = .green
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 12
button.titleLabel?.font = .systemFont(ofSize: 20, weight: .bold)
button.layer.masksToBounds = true
button.addTarget( self, action: #selector(sendButtonTapped), for: .touchUpInside)
return button
}()
let textView = UITextView()
private let passwordField: UITextField = {
let field = UITextField()
field.autocapitalizationType = .none
field.autocorrectionType = .no
field.returnKeyType = .done
field.layer.cornerRadius = 12
field.layer.borderWidth = 1
field.layer.borderColor = UIColor.lightGray.cgColor
field.placeholder = "Password"
field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 0))
field.leftViewMode = .always
field.backgroundColor = .white
field.isSecureTextEntry = true
return field
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .gray
view.addSubview(scrollView)
scrollView.addSubview(passwordField)
scrollView.addSubview(secureButton)
scrollView.addSubview(textView)
scrollView.addSubview(sendButton)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
passwordField.frame = CGRect(x: 30,
y: 100,
width: scrollView.width-60,
height: 52)
secureButton.frame = CGRect(x: 30,
y: passwordField.bottom+10 ,
width: scrollView.width-60,
height: 30)
textView.frame = CGRect(x: 30,
y: secureButton.bottom+10 ,
width: scrollView.width-60,
height: 30)
sendButton.frame = CGRect(x: 30,
y: textView.bottom+10 ,
width: scrollView.width-60,
height: 30)
}
#objc func securebuttonTapped() {
let text = passwordField
text.isSecureTextEntry = !text.isSecureTextEntry
}
#objc func sendButtonTapped() {
let text = passwordField
textView.inputView = text
print("send button tapped")
}
}
Swift 5
if you want to pass the data in the same controller its very simple. just asign the text to the textField on button Pressed
var textField = UITexField()
#objc func sendButtonTapped() {
// here you will assign the text you got from the password field to watever textfield you want, whether it is secure text or simple text.
textField.text = passwordField.text
print("send button tapped")
}
if you want to pass that text to some other ViewController you need to send like this
let vc = UIStoryboard(name: "Main", bundle:
nil).instantiateViewController(withIdentifier: "YourViewController") as!
YourViewController
// here you will assign the text to the variable from other viewcontroller you
want to.
vc.text = "Enter the text here"
self.navigationController?.pushViewController(vc, animated: true)

Altering table cell header on action in swift

I have a header in my sectioned table view that contains a button that expands its cells when tapped, I have a right ward facing arrow in the header as well, and when the header is tapped I want to change that arrow image to a downward facing arrow, how can I alter the section's header? Specifically the arrowButton
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 50))
let button = UIButton(frame: CGRect(x: 0, y: 0, width: tableView.frame.width - 30, height: 50))
button.setTitle(tableDataSource[section][0].mod.modType!, for: .normal)
button.titleLabel?.font = UIFont(name: "Helvetica neue", size: 20)
button.addTarget(self, action: #selector(headerPressed(sender:)), for: .touchUpInside)
button.titleLabel?.textAlignment = .left
button.tag = section
let arrowButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
arrowButton.setImage(UIImage(systemName: "chevron.right", compatibleWith: nil), for: .normal)
header.addSubview(arrowButton)
header.addSubview(button)
header.backgroundColor = UIColor.green
return header
}
#objc func headerPressed(sender: UIButton){
if(tableDataSource[sender.tag][0].clicked == false){
tableDataSource[sender.tag][0].clicked = true
} else {
tableDataSource[sender.tag][0].clicked = false
}
let sections = IndexSet.init(integer: sender.tag)
tableView.reloadSections(sections, with: .fade)
}
You need to change this inside viewForHeaderInSection
let name = tableDataSource[section][0].clicked ? "chevron.right" : "chevron.left"
arrowButton.setImage(UIImage(systemName:name, compatibleWith: nil), for: .normal)
And calling this tableView.reloadSections(sections, with: .fade) will do the reload job

Why is my button not working in Swift Playgrounds?

I am trying to make a playground and I have a button that says "Let's play!" and moves into a new view controller.
I looked at the code from this website and put it into my code:
http://lab.dejaworks.com/ios-swift-3-playground-uibutton-action/
This is all of my code (like, all of it):
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
//Introduction
let view = UIView()
view.backgroundColor = .red
//title
func labelCool() {
let label = UILabel()
label.frame = CGRect(x: 50, y: 300, width: 400, height: 100)
label.text = "Add-Add - A Wonderful Game!"
//label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.numberOfLines = 3
label.font = UIFont(name: "HelveticaNeue-Bold", size: 30)
UILabel.animate (withDuration: 10.0, animations:{
label.textColor = .black
})
UILabel.animate(withDuration: 5.0, animations:{
label.textColor = .blue
})
view.addSubview(label)
}
labelCool()
//subtitle
let subtitle = UILabel()
subtitle.frame = CGRect(x: 50, y: 400, width: 200, height: 50)
subtitle.text = "Curated and Created by Yours Truly, Adit Dayal!"
subtitle.numberOfLines = 4
self.view = view
view.addSubview(subtitle)
}
override func viewDidLoad() {
class Responder : NSObject {
#objc func action() {
print("Yay!")
}
}
let responder = Responder()
//next page
let button = UIButton(frame : CGRect(x: 0, y: 500, width: 200, height: 50))
button.setTitle("Let's Play!", for: .normal)
button.backgroundColor = .blue
button.addTarget(responder, action: #selector(Responder.action), for: .touchUpInside)
view.addSubview(button)
}
}
class gameViewController: UIViewController {
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
For now, I just want the button to display "Yay!" when clicked, but it is doing nothing!
Does anyone know why? (I'm on a bit of a time constraint)
Thank you so much,
Adit Dayal
Your Responder class is inside the viewDidLoad() function put the class outside like so
class Responder : NSObject {
#objc func action() {
print("Yay!")
}
}
override func viewDidLoad() {
let responder = Responder()
//next page
let button = UIButton(frame : CGRect(x: 0, y: 500, width: 200, height: 50))
button.setTitle("Let's Play!", for: .normal)
button.backgroundColor = .blue
button.addTarget(responder, action: #selector(responder.action), for: .touchUpInside)
view.addSubview(button)
}
The problem is that you are creating the responder object inside the viewDidLoad, as a local variable; this cause the object to be destroyed when the function ends (but we want that object alive even after). You have to retain that object, so instead of creating a local variable, create an instance variable by simply saving it as a class scope:
class Responder : NSObject {
#objc func action() {
print("Yay!")
}
}
let responder = Responder() // this is now outside the viewDidLoad, so it's an instance variable
override func viewDidLoad() {
//next page
let button = UIButton(frame : CGRect(x: 0, y: 500, width: 200, height: 50))
button.setTitle("Let's Play!", for: .normal)
button.backgroundColor = .blue
button.addTarget(responder, action: #selector(Responder.action), for: .touchUpInside)
view.addSubview(button)
}

Hiding and showing (subviews) button or change title?

I have a problem with my subviews. I have 2 visible buttons and 1 which should show after click the first one. More Precisely, i have Start Button, Reset Button and Stop Button. On load should show just Start and Reset button, but when I press Start Button the Reset button should hide and stop button should show. Syntax like isHidden doesn't works. What is the problem?
Star, Stop and Reset Button:
var stopButton: UIButton{
let stopButton = UIButton(frame: CGRect(x: 220, y: 50, width: 100, height: 100))
stopButton.backgroundColor = .white
stopButton.setTitle("Stop", for: .normal)
stopButton.addTarget(self, action: #selector(stopButtonAction), for: .touchUpInside)
stopButton.layer.cornerRadius = 50
stopButton.layer.masksToBounds = true
stopButton.isHidden = true
return stopButton
}
var resetButton: UIButton{
let resetButton = UIButton(frame: CGRect(x: 220, y: 50, width: 100, height: 100))
resetButton.backgroundColor = .red
resetButton.setTitle("Reset", for: .normal)
resetButton.addTarget(self, action: #selector(resetButtonAction), for: .touchUpInside)
resetButton.layer.cornerRadius = 50
resetButton.layer.masksToBounds = true
return resetButton
}
var startButton: UIButton{
let startButton = UIButton(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
startButton.backgroundColor = .green
startButton.setTitle("Start", for: .normal)
startButton.addTarget(self, action: #selector(startButtonAction), for: .touchUpInside)
startButton.layer.cornerRadius = 50
startButton.layer.masksToBounds = true
return startButton
}
Here i add this Subviews(this func also add UIView and it's called in viewDidLoad):
func addBottomView()
{
let orginX = (collectionView?.frame.minX)!
let orginY = (collectionView?.frame.maxY)!
let heightOfView = view.frame.height - (view.frame.height / 100) * 70
let bottomView = UIView(frame: CGRect(x: orginX, y: orginY, width: view.frame.width, height: heightOfView))
bottomView.backgroundColor = .orange
view.addSubview(bottomView)
bottomView.addSubview(stopButton)
bottomView.addSubview(startButton)
bottomView.addSubview(resetButton)
}
And here are my functions which are connected to this buttons:
func startButtonAction()
{
blinkAction()
print("START ACTION")
resetButton.isHidden = true
stopButton.isHidden = false
view.layoutSubviews()
}
func resetButtonAction()
{
print("RESET ACTION")
blinkAction()
}
func stopButtonAction()
{
print("STOP ACTION")
blinkAction()
resetButton.isHidden = false
stopButton.isHidden = true
view.layoutSubviews()
}
I add layoutSubviews method but it don't help. I also tried use self before name of button which is hidden but i also doesn't work. Any advice?
You can create button using computed properties with lazy keywoard
lazy var stopButton: UIButton = {
let stopButton = UIButton(frame: CGRect(x: 220, y: 50, width: 100, height: 100))
stopButton.backgroundColor = .yellow
stopButton.setTitle("Stop", for: .normal)
stopButton.addTarget(self, action: #selector(stopButtonAction), for: .touchUpInside)
stopButton.layer.cornerRadius = 50
stopButton.isHidden = true
stopButton.layer.masksToBounds = true
return stopButton
}()
lazy var resetButton: UIButton = {
let resetButton = UIButton(frame: CGRect(x: 220, y: 50, width: 100, height: 100))
resetButton.backgroundColor = .red
resetButton.setTitle("Reset", for: .normal)
resetButton.addTarget(self, action: #selector(resetButtonAction), for: .touchUpInside)
resetButton.layer.cornerRadius = 50
resetButton.layer.masksToBounds = true
return resetButton
}()
lazy var startButton: UIButton = {
let startButton = UIButton(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
startButton.backgroundColor = .green
startButton.setTitle("Start", for: .normal)
startButton.addTarget(self, action: #selector(startButtonAction), for: .touchUpInside)
startButton.layer.cornerRadius = 50
startButton.layer.masksToBounds = true
return startButton
}()
The computed properties startButton, stopButton, resetButton are not the SAME items as the ones added as subviews. Computed properties do not store a value, they give you methods to get values and set changes. So the actions you take there with isHidden do not apply to your view.
The reason of isHidden property not working well is that when your computed property variable you get a new instance of UIButton rather than old one. If you want to want to use computed properties then you should create lazy properties. So whenever you call property variable you'll get old one instance of UIButton.
Your properties always create new buttons, so your references will not be the same. When you set the isHidden, your button will be re-created so you set the isHidden propery of another button that is not added to bottomView.
Just use plain properties:
var stopButton: UIButton!
var resetButton: UIButton!
var startButton: UIButton!
Create the buttons:
func createButtons() {
let stopButton = UIButton(frame: CGRect(x: 220, y: 50, width: 100, height: 100))
stopButton.backgroundColor = .white
stopButton.setTitle("Stop", for: .normal)
stopButton.addTarget(self, action: #selector(stopButtonAction), for: .touchUpInside)
stopButton.layer.cornerRadius = 50
stopButton.layer.masksToBounds = true
stopButton.isHidden = true
let resetButton = UIButton(frame: CGRect(x: 220, y: 50, width: 100, height: 100))
resetButton.backgroundColor = .red
resetButton.setTitle("Reset", for: .normal)
resetButton.addTarget(self, action: #selector(resetButtonAction), for: .touchUpInside)
resetButton.layer.cornerRadius = 50
resetButton.layer.masksToBounds = true
let startButton = UIButton(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
startButton.backgroundColor = .green
startButton.setTitle("Start", for: .normal)
startButton.addTarget(self, action: #selector(startButtonAction), for: .touchUpInside)
startButton.layer.cornerRadius = 50
startButton.layer.masksToBounds = true
}
Add as subviews:
bottomView.addSubview(stopButton)
bottomView.addSubview(startButton)
bottomView.addSubview(resetButton)
And use them:
resetButton.isHidden = false
stopButton.isHidden = true

how to create radio buttons dynamically in swift?

I have the following buttons which are adding dynamically based on some condition. Now i need to change all added buttons behaviour as radio buttons. so that I can do some actions based on the selection..
var posX = 0
var posY = 0
if trim.contains("0"){
print("contaim 0")
let button1 = UIButton(frame: CGRect(x: posX, y: posY, width: 60, height: 20))
button1.setTitleColor(UIColor.blackColor(), forState: .Normal)
button1.setTitle("No", forState: .Normal)
button1.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
button1.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
myStackview.addSubview(button1)
posX = 60
}
if trim.contains("1") {
print("contaim 1")
let button2 = UIButton(frame: CGRect(x: posX, y: posY, width: 60, height: 20))
button2.setTitleColor(UIColor.blackColor(), forState: .Normal)
button2.setTitle("Less", forState: .Normal)
button2.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
button2.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
myStackview.addSubview(button2)
posX = posX + 60
}
if trim.contains("2"){
print("contaim 2")
let button3 = UIButton(frame: CGRect(x: posX, y: posY, width: 60, height: 20))
button3.setTitleColor(UIColor.blackColor(), forState: .Normal)
button3.setTitle("Half", forState: .Normal)
button3.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
button3.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
myStackview.addSubview(button3)
posX = posX + 60
}
I have set the buttonAction methods as below buts its not working
func buttonAction(sender: UIButton!) {
print("Button tapped")
sender.setImage(UIImage(named: "checkboxredtick.png")!, forState: .Normal)
}
let buttons = [UIButton]()
// create button1
let button1 = UIButton(frame: CGRect(x: posX, y: posY, width: 60, height: 20))
button1.setTitleColor(UIColor.blackColor(), forState: .Normal)
button1.setTitle("No", forState: .Normal)
button1.setImage(UIImage(named: "checkbox untick.png")!, forState: .Normal)
// if the selected button cannot be reclick again, you can use .Disabled state
button1.setImage(UIImage(named: "checkboxredtick.png")!, forState: .Selected)
button1.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
myStackview.addSubview(button1)
buttons.append(button1)
// create other buttons and add into buttons ...
func buttonAction(sender: UIButton!){
for button in buttons {
button.selected = false
}
sender.selected = true
// you may need to know which button to trigger some action
// let buttonIndex = buttons.indexOf(sender)
}
In case anyone finds this useful. Here is an example of how I use DLRadioButton library (https://github.com/DavydLiu/DLRadioButton) to create RadioButtons dynamically.
You can check a complete small project to show a working code in here https://github.com/omhack/DynamicRadioButtons
import UIKit
import DLRadioButton
//Delegate to manage the Polls
protocol QuestionsDialogDelegate : class{
func questionsAnswered(polls: [Poll])
}
class QuestionsDialog: UIViewController {
#IBOutlet weak var stackView: UIStackView!
#IBOutlet var rootView: UIView!
#IBOutlet weak var nestedView: UIView!
weak var delegate: QuestionsDialogDelegate?
var questions : [Question]!
var polls = [Poll]()
var serviceType : Int = 0
var indexView : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
//setting the stack view properties
stackView.alignment = UIStackViewAlignment.leading
stackView.axis = .vertical
}
//this is where the heavy logic, to create the dynamic radio buttons takes place
func showQuestions(){
if(questions.count <= 1){
rootView.frame.size.height = 200
nestedView.frame.size.height = 200
}else{
rootView.frame.size.height = 400
nestedView.frame.size.height = 400
}
for question in questions{
var otherButtons : [DLRadioButton] = []
let frame1 = CGRect(x: self.view.frame.size.width / 2 - 131, y: 350, width: 262, height: 17);
//we create a base radio button to use it as an anchor view
let firstRadioButton = createRadioButton(frame: frame1, title: "", color: UIColor.purple);
let label = UILabel()
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 17.0)
label.textColor = UIColor.darkGray.withAlphaComponent(0.85)
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.25
label.frame = CGRect(x: 0, y: 0, width: 200, height: 30)
label.text = question.question
self.stackView.insertArrangedSubview(label, at: self.indexView)
self.indexView += 1
let poll = Poll()
poll.idQuestion = question.idQuestion
var i = 0;
for answer in question.answers{
let frame = CGRect(x: self.view.frame.size.width / 2 - 131, y: 380 + 30 * CGFloat(i), width: 300, height: 17);
let radioButton = createRadioButton(frame: frame, title: answer.answer! + " ", color: UIColor.purple)
radioButton.tag = answer.idAnswer
radioButton.params["poll"] = poll
otherButtons.append(radioButton)
self.stackView.insertArrangedSubview(radioButton, at: self.indexView)
i += 1;
self.indexView += 1
}
firstRadioButton.otherButtons = otherButtons
firstRadioButton.isHidden = true
firstRadioButton.otherButtons[1].isSelected = true
}
}
//Method to create a custom button
private func createRadioButton(frame : CGRect, title : String, color : UIColor) -> MyDLUIButton {
let radioButton = MyDLUIButton(frame: frame);
radioButton.titleLabel?.translatesAutoresizingMaskIntoConstraints = false
radioButton.titleLabel!.font = UIFont.systemFont(ofSize: 14);
radioButton.setTitle(title, for: []);
radioButton.setTitleColor(UIColor.darkGray, for: []);
radioButton.iconColor = color;
radioButton.indicatorColor = color;
radioButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left;
radioButton.addTarget(self, action: #selector(QuestionsDialog.selectedAnswer(_:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(radioButton);
return radioButton;
}
#objc func selectedAnswer(_ sender: MyDLUIButton){
let poll = sender.params["poll"] as? Poll
poll?.idAnswer = sender.tag
if let row = self.polls.index(where: {$0.idQuestion == poll?.idQuestion}) {
self.polls[row] = poll!
}else{
self.polls.append(poll!)
}
print("polls size: \(self.polls.count)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidDisappear(_ animated: Bool) {
if(self.polls.count < self.questions.count){
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "questionsDialogDismissed"), object: nil)
}
}
#IBAction func requestService(_ sender: UIButton) {
delegate?.questionsAnswered(polls: self.polls)
}
}
class MyDLUIButton: DLRadioButton{
var params: Dictionary<String, Any>
override init(frame: CGRect) {
self.params = [:]
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
self.params = [:]
super.init(coder: aDecoder)
}
}
I would create a tag for every UIButton, then add your UIButton to be send to your ButtonAction:
button.tag = 0
button.addTarget(object, action: #selector(YourViewController.buttonAction(_:)),
forControlEvents: .TouchUpInside)
func buttonAction(sender: UIButton!) {
let selectedButton = sender as! UIButton
print(selectedButton.tag) // here stands the correct button which is pressed
}
You could also create an Array containing all Buttons, for example:
let myButtons = [UIButton]()
let button1 = UIButton()...
button1.tag = 0
myButtons.add(button1)
And now change it like this way:
myButtons[0].setImage(.....)
Where 0 is your first button (so with tag 0) // you should set your tags in the same order in which you append it to your myButtons Array.

Resources