create a if statement where only one button at a time can have a border - swift

I want my swift code to use a if statement or another sequence to only display a border on one of the buttons if click at a time. So a border can only be seen on one button at a time that button would be the last one pressed. I know I could say layer.border with 0 on each button that should be selected but I want to see if there is a more efficient way to do this.
import UIKit
class ViewController: UIViewController {
var ba = UIButton()
var bb = UIButton()
var bc = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
[ba,bb,bc].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
}
ba.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
bb.frame = CGRect(x: 100, y: 0, width: 100, height: 100)
bc.frame = CGRect(x: 200, y: 0, width: 100, height: 100)
ba.backgroundColor = .blue
bb.backgroundColor = .orange
bc.backgroundColor = .darkGray
ba.addTarget(self, action: #selector(pressa), for: .touchDown)
bb.addTarget(self, action: #selector(pressb), for: .touchDown)
bc.addTarget(self, action: #selector(pressc), for: .touchDown)
}
#objc func pressa(){
ba.layer.borderWidth = 2
}
#objc func pressb(){
bb.layer.borderWidth = 2
}
#objc func pressc(){
bc.layer.borderWidth = 2
}
}

you can add target to all buttons at the forEach and be only one method as #Sh_Khan mention
import UIKit
class ViewController: UIViewController {
var ba = UIButton()
var bb = UIButton()
var bc = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
[ba,bb,bc].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
$0.addTarget(self, action: #selector(pressAll(_:)), for: .touchDown)
}
ba.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
bb.frame = CGRect(x: 100, y: 0, width: 100, height: 100)
bc.frame = CGRect(x: 200, y: 0, width: 100, height: 100)
ba.backgroundColor = .blue
bb.backgroundColor = .orange
bc.backgroundColor = .darkGray
}
#objc func pressAll(_ sender:UIButton) {
[ba,bb,bc].forEach { $0.layer.borderWidth = 0 } // reset all
sender.layer.borderWidth = 2
}
}

See how you have used an array in [ba,bb,bc].forEach { ... } to reduce code duplication? Using arrays is the key. Rather than putting the three buttons in an array inline like that, create a property instead:
var buttons: [UIButton]!
override func viewDidLoad() {
super.viewDidLoad()
buttons = [ba,bb,bc]
buttons.forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
$0.addTarget(self, action: #selector(buttonPressed), for: .touchDown)
}
...
}
I have used the same selector buttonPressed for all three buttons. buttonPressed can accept a parameter of type UIButton, that tells us which button is pressed:
#objc func buttonPressed(_ sender: UIButton) {
buttons.forEach { ba.layer.borderWidth = 0 } // deselect all buttons first...
sender.layer.borderWidth = 2 // select the tapped button
}
If you have more than 3 buttons to manage, I suggest you don't use UIButtons at all. You should use a UICollectionView. (Learn how to use them) This view will handle the selection for you. It also allows scrolling when there's not enough space to show all the buttons. You just need to create a custom UICollectionViewCell and override its isSelected property:
override var isSelected: Bool {
didSet {
if isSelected {
self.layer.borderWidth = 2
} else {
self.layer.borderWidth = 0
}
}
}

It could be 1 method like this
[ba,bb,bc].forEach { $0.addTarget(self, action: #selector(pressAll(_:)), for: .touchDown) }
}
#objc func pressAll(_ sender:UIButton) {
[ba,bb,bc].forEach { $0.layer.borderWidth = 0 } // reset all
sender.layer.borderWidth = 2
}

Related

iOS UIkit custom segmented buttons

I'm looking to create a view with these buttons. There is a background animation when one of the button touched.
Not sure how to do this.
Is custom segmented buttons the way to go?
I went with custom control
import UIKit
protocol MSegmentedControlDelegate:AnyObject {
func segSelectedIndexChange(to index:Int)
}
class MSegmentedControl: UIControl {
private var buttonTitles:[String]!
private var buttons: [UIButton]!
private var selectorView: UIView!
var textColor:UIColor = .black
var selectorViewColor: UIColor = .white
var selectorTextColor: UIColor = .red
weak var delegate:MSegmentedControlDelegate?
public private(set) var selectedIndex : Int = 0
convenience init(frame:CGRect,buttonTitle:[String]) {
self.init(frame: frame)
self.buttonTitles = buttonTitle
}
override func draw(_ rect: CGRect) {
super.draw(rect)
self.backgroundColor = UIColor.white
updateView()
}
func setButtonTitles(buttonTitles:[String]) {
self.buttonTitles = buttonTitles
self.updateView()
}
func setIndex(index:Int) {
buttons.forEach({ $0.setTitleColor(textColor, for: .normal) })
let button = buttons[index]
selectedIndex = index
button.setTitleColor(selectorTextColor, for: .normal)
let selectorPosition = frame.width/CGFloat(buttonTitles.count) * CGFloat(index)
UIView.animate(withDuration: 0.2) {
self.selectorView.frame.origin.x = selectorPosition
}
}
#objc func buttonAction(sender:UIButton) {
for (buttonIndex, btn) in buttons.enumerated() {
btn.setTitleColor(textColor, for: .normal)
if btn == sender {
let selectorPosition = frame.width/CGFloat(buttonTitles.count) * CGFloat(buttonIndex)
selectedIndex = buttonIndex
delegate?.segSelectedIndexChange(to: selectedIndex)
UIView.animate(withDuration: 0.3) {
self.selectorView.frame.origin.x = selectorPosition
}
btn.setTitleColor(selectorTextColor, for: .normal)
}
}
}
}
//Configuration View
extension MSegmentedControl {
private func updateView() {
createButton()
configSelectorView()
configStackView()
}
private func configStackView() {
let stack = UIStackView(arrangedSubviews: buttons)
stack.axis = .horizontal
stack.alignment = .fill
stack.distribution = .fillEqually
addSubview(stack)
stack.translatesAutoresizingMaskIntoConstraints = false
stack.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
stack.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
stack.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
stack.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
}
private func configSelectorView() {
let selectorWidth = frame.width / CGFloat(self.buttonTitles.count)
selectorView = UIView(frame: CGRect(x: 0, y: 8, width: selectorWidth, height: 32))
selectorView.backgroundColor = selectorViewColor
selectorView.layer.cornerRadius = 16
selectorView.layer.opacity = 0.5
addSubview(selectorView)
}
private func createButton() {
buttons = [UIButton]()
buttons.removeAll()
subviews.forEach({$0.removeFromSuperview()})
for buttonTitle in buttonTitles {
let button = UIButton(type: .system)
button.setTitle(buttonTitle, for: .normal)
button.addTarget(self, action:#selector(MSegmentedControl.buttonAction(sender:)), for: .touchUpInside)
button.setTitleColor(textColor, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
buttons.append(button)
}
buttons[0].setTitleColor(selectorTextColor, for: .normal)
}
}
Usage:
private let segControl: MSegmentedControl = {
let segControl = MSegmentedControl(
frame: CGRect(x: 0, y: 240, width: 280, height: 50),
buttonTitle: ["Average","Total","Pending"])
segControl.textColor = M.Colors.greyWhite
segControl.selectorTextColor = .white
return segControl
}()
To access index change event:
Implement the delegate on parent view:
addSubview(segControl)
segControl.delegate = self
Delegate:
func segSelectedIndexChange(to index: Int) {
switch index {
case 0: print("Average")
case 1: print("Total")
case 2: print("Pending")
default: break
}
}
Result:

“Unrecognized selector sent to instance” in UIView class when calling addTarget

I am trying to create a DropDownMenu class, but when I try to call addTarget to one of the buttons, this error comes up.
unrecognized selector sent to instance 0x7fd167f06120' terminating with uncaught exception of type NSException
I would really appreciate any help and no answer is a bad one!
Here is my entire class
class DropDownMenu: UIView {
// Main button or Pre
var main: UIButton! = UIButton(frame: CGRect(x: 0, y: 0, width: 46, height: 30))
var view: UIView!
// Title
var buttonTitles: [String]! = [""]
var titleColor: UIColor! = UIColor.black
var font: UIFont! = UIFont.systemFont(ofSize: 18)
// Individual Button
var buttonsBorderWidth: CGFloat! = 0
var buttonsBorderColor: UIColor? = UIColor.white
var buttonsCornerRadius: CGFloat! = 0
var color: UIColor! = UIColor.clear
// Button Images
var buttonsImageEdgeInsets: UIEdgeInsets? = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
var images: [UIImage]? = nil
// Onclick stuff
var target: UIViewController!
private var currentSelected: String? = nil
private var optionsStack = UIStackView()
init(main: UIButton) {
self.main = main
super.init(frame: CGRect())
}
func createDropDownMenu() {
main.addTarget(target, action: #selector(DropDownMenu.openDropdown(_:)), for: .touchUpInside)
print("Button Target?: \(main.allTargets), self.target: \(String(describing: target))")
let mainFrame = main.frame
optionsStack.frame = CGRect(x: mainFrame.minX, y: mainFrame.maxY, width: mainFrame.width, height: CGFloat(buttonTitles.count) * mainFrame.height)
optionsStack.axis = .vertical
view.addSubview(optionsStack)
var y: CGFloat! = 0
for title in buttonTitles {
let button = UIButton(frame: CGRect(x: 0, y: y, width: mainFrame.width, height: mainFrame.height))
button.setTitle(title, for: .normal)
button.setTitleColor(titleColor, for: .normal)
button.backgroundColor = color
button.titleLabel?.font = font
button.addTarget(target, action: #selector(DropDownMenu.onclick), for: .touchUpInside)
y += mainFrame.height
optionsStack.addArrangedSubview(button)
}
for button in optionsStack.arrangedSubviews {
button.isHidden = true
button.alpha = 0
}
}
#objc private func openDropdown(_ sender: UIButton) {
print("sender: \(String(describing: sender))")
optionsStack.arrangedSubviews.forEach { (button) in
UIView.animate(withDuration: 0.7) {
button.isHidden = !button.isHidden
button.alpha = button.alpha == 0 ? 1 : 0
self.view.layoutIfNeeded()
}
}
}
#objc private func onclick(_ sender: UIButton) {
let title = sender.titleLabel!.text
print(title as Any)
main.setTitle(title, for: .normal)
optionsStack.arrangedSubviews.forEach { (button) in
UIView.animate(withDuration: 0.7) {
button.isHidden = true
button.alpha = 0
}
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Here is the code and creation of the object in ViewController
let grade = UIButton(frame: CGRect(x: 50, y: 300, width: 80, height: 30))
grade.layer.borderWidth = 1
grade.setTitle("Grade", for: .normal)
grade.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
grade.setTitleColor(UIColor.black, for: .normal)
let gradeDP = DropDownMenu(main: main)
gradeDP.buttonTitles = ["Title 1", "Title 2", "Title 3"]
gradeDP.color = UIColor.gray
gradeDP.target = self
gradeDP.titleColor = UIColor.white
gradeDP.view = view
view.addSubview(grade)
gradeDP.createDropDownMenu()
The first print statement in the createDropDownMenu() function prints...
Button Target?: [AnyHashable(<HomeworkHelp.DropDownMenu: 0x7ffb555200b0; frame = (0 0; 0 0); layer = <CALayer: 0x600002bdf5c0>>)], self.target: Optional(<HomeworkHelp.CreateAccountViewController: 0x7ffb5550a7b0>)
After editing it with the help of mightknow I came up with this class. It doesn't have any onclick actions for the mainButton in it.
class DropDownMenu: UIStackView {
var options: [String]! = [] // Labels for all of the options
var titleButton: UIButton! = UIButton() // The Main Title Button
init(options: [String]) {
self.options = options
let mainFrame = titleButton.frame
super.init(frame: CGRect(x: mainFrame.minX, y: mainFrame.maxY, width: mainFrame.width, height: mainFrame.height * CGFloat(options.count)))
var y: CGFloat = 0
for title in self.options {
let button = UIButton(frame: CGRect(x: 0, y: y, width: self.frame.width, height: mainFrame.height))
button.setTitle(title, for: .normal)
button.setTitleColor(titleButton.titleLabel?.textColor, for: .normal)
button.backgroundColor = titleButton.backgroundColor
button.addTarget(self, action: #selector(dropDownOptionClicked(_:)), for: .touchUpInside)
button.isHidden = true
button.alpha = 0
self.addArrangedSubview(button)
y += 1
}
}
#objc func openDropDown(_ sender: UIButton) {
print("Open DropDownMenu")
for button in self.arrangedSubviews {
UIView.animate(withDuration: 0.7) {
button.isHidden = !button.isHidden
button.alpha = button.alpha == 0 ? 1 : 0
self.layoutIfNeeded()
self.superview?.layoutIfNeeded()
}
}
}
#objc private func dropDownOptionClicked(_ sender: UIButton) {
print(sender.titleLabel?.text as Any)
}
init() {
super.init(frame: CGRect.zero)
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
And than my ViewController is ...
let dp = DropDownMenu(options: ["Label 1", "Label 2", "Label 3"])
let titleButton = UIButton(frame: CGRect(x: 100, y: 300, width: 180, height: 40))
titleButton.backgroundColor = UIColor.white
titleButton.setTitle("DropDownMenu", for: .normal)
titleButton.setTitleColor(UIColor.black, for: .normal)
titleButton.layer.borderWidth = 2
titleButton.addTarget(self, action: #selector(dp.openDropDown(_:)), for: .touchUpInside)
dp.titleButton = titleButton
The error ...
Button Target?: [AnyHashable(<HomeworkHelp.DropDownMenu: 0x7ffb555200b0; frame = (0 0; 0 0); layer = <CALayer: 0x600002bdf5c0>>)], self.target: Optional(<HomeworkHelp.CreateAccountViewController: 0x7ffb5550a7b0>)
still comes up and I am clueless as to why.
You're setting the target as a UIViewController when the method you're calling is actually a method of the DropDownMenu class. What you need to do is set the target to self instead of the target property:
main.addTarget(self, action: #selector(DropDownMenu.openDropdown(_:)), for: .touchUpInside)
EDIT: In response to your comment, here is the code I'm using to test it. There are some layout/color choices I made just to make it clear to me, but this works:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let main = UIButton(frame: CGRect(x: 0, y: 100, width: 80, height: 30))
main.layer.borderWidth = 1
main.setTitle("Grade", for: .normal)
main.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
main.setTitleColor(UIColor.black, for: .normal)
let gradeDP = DropDownMenu(main: main)
gradeDP.buttonTitles = ["Title 1", "Title 2", "Title 3"]
gradeDP.color = UIColor.gray
gradeDP.target = self
gradeDP.titleColor = UIColor.white
gradeDP.view = UIView()
self.view.addSubview(gradeDP)
let b = self.view.bounds
gradeDP.frame = CGRect(x: b.minX, y: b.minY, width: b.width, height: b.height/2)
gradeDP.backgroundColor = UIColor.purple
gradeDP.target = self
gradeDP.addSubview(gradeDP.main)
gradeDP.createDropDownMenu()
}}
As for your code, I'm going on the assumption that the code you added in the second part of your question is inside your ViewController's viewDidLoad() method, and that the main variable you're using to initialize your DropDownMenu is an instance variable of your ViewController, because I'm not seeing it anywhere else in scope. If that's the case, there are definitely some issues. They are:
You never actually add gradeDP to your view hierarchy. If that's what the line gradeDP.view = view is supposed to do, it's not. What that code actually does is set the view property of gradeDP to be a reference to the ViewController's view property. And, unless there is code in your DropDownMenu class that you haven't included, you're not actually using that reference for anything. So, you can get rid of that line entirely, and the view property in your DropDownMenu class. If what you're trying to do is set the ViewController's view to be gradeDP, that code would be self.view = gradeDP, but I don't actually recommend doing it that way. A UIViewController's view property is used in some special functionality and probably shouldn't be messed with much. You probably want to add gradeDP as a subview, like I did in my code above.
The grade button you created is not used by your DropDownMenu. I'm guessing you meant to initialize with that instead of the main variable (that is out of scope of your code), like this:
let gradeDP = DropDownMenu(main: grade)
In short, unless there is code elsewhere that you haven't shared, what your code above does is create a UIButton labeled "Grade" that is visible but doesn't actually do anything (and isn't part of your DropDownMenu), and a DropDownMenu that isn't actually visible, but would have a main button that calls openDropdown(_:) if it was. I'm guessing that's not how it's supposed to work. Hopefully the code I provided above helps get you where you want to be, though.
As for suggestions with rebuilding your class so it works properly, you may want to start with something like this:
class DropDownMenu : UIView {
var dropdownOptions : [String] = []
private var titleButton : UIButton = UIButton()
private var optionsStack : UIStackView = UIStackView()
private var optionsButtons : [UIButton] = []
#objc private func openDropdown(_ sender: UIButton) {
// Add code to make dropdown options appear. There are multiple ways of doing this. For instance, the optionsButtons could be hidden and then unhidden when it's clicked, or they could be created only once the button is clicked.
}
#objc private func selectedOption(_ sender: UIButton) {
// Code here for when option is selected
}
init(options: [String]) {
self.dropdownOptions = options
super.init(frame: CGRect.zero)
// Customize all of your subviews here, and add them to your DropDownMenu (as subviews)
// Add openDropdown(_:) target to self.titleButton
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
A lot of the code you have already written for your original version of the class can go inside the functions there. Also, there is a lot of unnecessary code in your original version. For example, the target variable is unused once you fixed the original error issue, the view variable is obsolete, and the createDropDownMenu() function is unnecessary because all of that code can go either in the init(options:) or openDropdown(_:) functions.
Then, if you choose to build out a class using that template, you would implement it in your ViewController's viewDidLoad() method with the code:
let dropdown = DropDownMenu(titles: ["Title 1", "Title 2", "Title 3"])
self.view.addSubview(dropdown)
// Follow that with layout code that ensures it's the proper size and in the proper location
I hope that combined with my comments make sense, are helpful, and aren't too overwhelming. What I recommend doing is starting a new empty project (or target) and building your class and adding it to a ViewController with nothing else in it. That's a good way to isolate it and check and make sure everything looks and works right. In case you want an alternate suggestion with how to build your class, you can actually try making DropDownMenu be a subclass of UIStackView (instead of UIView) with the main button and all option buttons being arranged subviews. This might actually be simpler, because it kind of cuts out the middleman, if you will, and all you'd need to do when opening/closing the dropdown is add/remove views from the .arrangedSubviews property.
Also important is that if your view needs to pass information (such as which option is selected) back to the ViewController, make sure the reference to the ViewController is marked weak so you don't create a retain cycle.
On a final note, if you're disappointed that there isn't a quick fix to get the original class to work and want to keep trying at that, there might be some way to cobble together a solution (like the code from my first answer, which does actually work...), but ultimately it will probably only cause more issues further down the line. So, best of luck with everything.
I finally figured it out! The target has to be the DropDownMenu.
titleButton.addTarget(dp, action: #selector(dp.openDropDown(_:)), for: .touchUpInside)
Here is the rest of the code...
let titleButton = UIButton(frame: CGRect(x: 50, y: 290, width: 100, height: 40))
titleButton.backgroundColor = UIColor.white
titleButton.setTitle("Grade", for: .normal)
titleButton.setTitleColor(UIColor.black, for: .normal)
titleButton.layer.borderWidth = 2
titleButton.layer.cornerRadius = 10
let dp = DropDownMenu(options: ["1", "Freshman", "Sophomore", "Junior", "Senior", "College"])
dp.titleButton = titleButton
dp.target = self
dp.borderWidth = 2
dp.spacing = 5
dp.cornerRadius = 10
dp.bgColor = UIColor.white
Adding it to subviews and creating it...
view.addSubview(titleButton)
view.addSubview(dp)
dp.createDropDownMenu()

Use Uitapgesture recognizer on multiple image views that are not declared

My swift code uses func addBox to add and append image views to the uiview controller. All I want to do is when one of the image views are tapped is for func viewClicked to be activated. Right now nothing is happening and nothing is being written into the debug area.
import UIKit
class ViewController: UIViewController {
var ht = -90
var ww = 80
var hw = 80
var arrTextFields = [UIImageView]()
var b7 = UIButton()
override func viewDidLoad() {
[b7].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
$0.backgroundColor = .systemOrange
}
b7.frame = CGRect(x: view.center.x-115, y: view.center.y + 200, width: 70, height: 40)
b7.addTarget(self, action: #selector(addBOx), for: .touchUpInside)
for view in self.arrTextFields {
view.isUserInteractionEnabled = true
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewClicked)))
}
}
#objc func viewClicked(_ recognizer: UITapGestureRecognizer) {
print("tap")
}
//func that adds imageview.
#objc func addBOx() {
let subview = UIImageView()
subview.isUserInteractionEnabled = true
arrTextFields.append(subview)
view.addSubview(subview)
subview.frame = CGRect(x: view.bounds.midX - 0, y: view.bounds.midY + CGFloat(ht), width: CGFloat(ww), height: 35)
subview.backgroundColor = .purple
ht += 50
arrTextFields.append(subview)
}
}
You need to enable user interation
for view in self.arrTextFields {
view.isUserInteractionEnabled = true
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewClicked)))
}
#objc func viewClicked(_ recognizer: UITapGestureRecognizer) {
print("tap")
}

how do I make another button appear if I pressed one button in swift

I am trying to make a game where if I press a button it can spawn another button in another area so you can click and keep doing that, every time you press the button you should get a point. I don't know how to spawn another button when I pressed one button.
// this is the code
var monkeyPosition : Int = 1
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.25, alpha: 1.0)
view.backgroundColor = UIColor(white: 0.25, alpha: 1.0)
view.addSubview(makeButtonSpawn())
view.addSubview(makeButtonSpawn2())
}
#IBAction func monkeyPlayer(_ sender: UIButton) {
if sender.tag == 1 && (monkeyPosition == 1) {
makeButtonSpawn2().isHidden = false
}
}
func makeButtonSpawn() -> UIButton {
let monkey = UIButton(type: UIButton.ButtonType.system)
//Set a frame for the button. Ignored in AutoLayout/ Stack Views
monkey.frame = CGRect(x: 30, y: 30, width: 90, height: 90)
monkey.backgroundColor = UIColor.blue
makeButtonSpawn().isHidden = true
return monkey
}
func makeButtonSpawn2() -> UIButton {
let monkey = UIButton(type: UIButton.ButtonType.system)
//Set a frame for the button. Ignored in AutoLayout/ Stack Views
monkey.frame = CGRect(x: 80, y: 80, width: 90, height: 90)
monkey.backgroundColor = UIColor.blue
makeButtonSpawn2().isHidden = true
return monkey
}
Create instance variables for your buttons, then you will be able to access them from places in your class. Also you can set its properties inside variable closure instead of declaring method
class ViewController: UIViewController {
var button1: UIButton = {
let button = UIButton()
button.frame = CGRect(x: 30, y: 30, width: 90, height: 90)
button.backgroundColor = .blue
return button
}()
var button2: UIButton = {
let button = UIButton()
button.frame = CGRect(x: 80, y: 80, width: 90, height: 90)
button.backgroundColor = .blue
button.isHidden = true
return button
}()
}
Next, you need to add your buttons as subviews to main view and you need to add target for them
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.25, alpha: 1.0)
view.backgroundColor = UIColor(white: 0.25, alpha: 1.0)
view.addSubview(button1)
view.addSubview(button2)
button1.addTarget(self, action: #selector(button1Pressed(_:)), for: .touchUpInside)
button2.addTarget(self, action: #selector(button2Pressed(_:)), for: .touchUpInside)
}
#objc func button1Pressed(_ sender: UIButton) {
}
#objc func button2Pressed(_ sender: UIButton) {
}
Finally, you can unhide second button when first button is pressed
#objc func button1Pressed(_ sender: UIButton) {
if monkeyPosition == 1 {
button2.isHidden = false
}
}

Is there any easier way to view UIImageView programmatically?

I have 8 buttons and I want to display a picture every time I press the buttons.
What I wonder is, do I need to have 8 functions to display these images?
Or is there any easier ways?
Here is how I've done it, it works as it should, but I do not want to repeat the same things over and over again?
var imageView1:UIImageView!
var imageView2:UIImageView!
var imageView3:UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
showImage1()
showImage2()
showImage3()
tapGestureRecognizerFunc()
}
#objc func button1Tap() {
if self.imageView1.isHidden {
self.imageView1.isHidden = false
}else{
self.imageView1.isHidden = true
}
}
#objc func button2Tap() {
if self.imageView2.isHidden {
self.imageView2.isHidden = false
}else{
self.imageView2.isHidden = true
}
}
#objc func button3Tap() {
if self.imageView3.isHidden {
self.imageView3.isHidden = false
}else{
self.imageView3.isHidden = true
}
}
func showImage1() {
imageView1 = UIImageView(frame: CGRect(x: 271, y: 8, width: 29, height: 29))
imageView1.image = UIImage(named: "Done.png")
imageView1.contentMode = .scaleAspectFit
View1.addSubview(imageView1)
imageView1.isHidden = true
}
func showImage2() {
imageView2 = UIImageView(frame: CGRect(x: 271, y: 8, width: 29, height: 29))
imageView2.image = UIImage(named: "Done.png")
imageView2.contentMode = .scaleAspectFit
View2.addSubview(imageView2)
imageView2.isHidden = true
}
func showImage3() {
imageView2 = UIImageView(frame: CGRect(x: 271, y: 8, width: 29, height: 29))
imageView2.image = UIImage(named: "Done.png")
imageView2.contentMode = .scaleAspectFit
View3.addSubview(imageView2)
imageView2.isHidden = true
}
func tapGestureRecognizerFunc () {
let exercise1Tap = UITapGestureRecognizer(target: self, action: #selector(button1Tap))
exercise1Tap.numberOfTapsRequired = 2
View1.addGestureRecognizer(exercise1Tap)
let exercise2Tap = UITapGestureRecognizer(target: self, action: #selector(button2Tap))
exercise2Tap.numberOfTapsRequired = 2
View2.addGestureRecognizer(exercise2Tap)
let exercise3Tap = UITapGestureRecognizer(target: self, action: #selector(button3Tap))
exercise3Tap.numberOfTapsRequired = 2
View3.addGestureRecognizer(exercise3Tap)
}
yes i'm newbie
Since I don't know, where and how you create the Buttons it is difficult to answer.
The following is just a tip.
You should use an array of UIImageView
Your callback should use the Form buttonAction(sender : UIButton)
You could use a tag for the button to get the number of the corresponding button
For example:
class ViewController: UIViewController {
var imageviews : [UIImageView] = []
override func viewDidLoad() {
super.viewDidLoad()
for i in 1...8 {
let imageview = UIImageView()
view.addSubview(imageview)
imageview.tag = i
imageviews.append(imageview)
let button = UIButton(frame: CGRect(x: 0, y: CGFloat(i)*50.0, width: 100, height: 30))
view.addSubview(button)
button.setTitle("Button \(i)", for: .normal)
button.setTitleColor(.black, for: .normal)
button.tag = i
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
}
}
#objc func buttonAction(sender : UIButton) {
let index = sender.tag
print("Button \(index) pressed")
imageviews[index].isHidden = !imageviews[index].isHidden
}
}