How can I change my custom cell background when pressing a button? - swift

I have a CollectionView and a Button inside of an UIView. The purpose of the button is change the theme of the app, and I can change all colors, except for the backgroundColor of a nameContainerView on my TatodexCell (a custom cell).
I can't figure out how to access that property, and then, change the color I want.
THE FOLLOWING CODE IS LOCATED ON MY TatodexController FILE
My button property is:
let buttonChangeTheme: UIButton? = {
let button = UIButton()
button.setTitle("Change to blue theme", for: .normal)
button.addTarget(self, action: #selector(themeButtonClicked), for: .touchUpInside)
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.layer.borderWidth = 3
button.layer.borderColor = Colors.mainBlack?.cgColor
button.backgroundColor = Colors.darkBlue
button.tintColor = Colors.mainWhite
return button
}()
My button-func is this one:
#objc func themeButtonClicked() {
clickCheck = !clickCheck
if clickCheck {
navigationController?.navigationBar.barTintColor = Colors.lightBlue
collectionViewPokemon?.backgroundColor = Colors.darkBlue
buttonChangeTheme?.backgroundColor = Colors.darkRed
buttonChangeTheme?.setTitle("Return to red theme", for: .normal)
}
else {
navigationController?.navigationBar.barTintColor = Colors.lightRed
collectionViewPokemon?.backgroundColor = Colors.darkRed
buttonChangeTheme?.backgroundColor = Colors.darkBlue
buttonChangeTheme?.setTitle("Change to blue theme", for: .normal)
}
}
THE FOLLOWING CODE IS LOCATED ON MY TatodexCell FILE
The nameContainerView I wanna modify it's bg color is:
lazy var nameContainerView: UIView = {
let nameView = UIView()
nameView.backgroundColor = Colors.lightRed
nameView.addSubview(nameLabel)
nameLabel.center(inView: nameView)
return nameView
}()
My goal is to change nameView.backgroundColor = Colors.lightRed to nameView.backgroundColor = Colors.lightBlue, but I can't access that property.
I would really appreciate any help or advice. Perhaps the solution is hiding in plain sight, but I've tried many ways and none of them worked. Let me know if another chunk of code is needed to be shown.

If you implement the tintColorDidChange() method in your custom collection view cell, and in that method, you set the cell's background color to the tint color, then when you change the owning UICollectionView's tint color, the cells's tintColorDidChange() methods will fire and you'll see the change.

Related

How can I add two images (one at the left and one on the right side) in a button in Xcode programaticly? I need also a title of a button

func setupButtonUI() {
if let detailsImage = UIImage(named: "detalji_icon") {
setImage(detailsImage, for: .normal)
contentHorizontalAlignment = .left
contentVerticalAlignment = .center
}
if let arrowImage = UIImage(named: "posalji_zahtev_black_icon") {
setImage(arrowImage, for: .normal)
contentHorizontalAlignment = .right
contentVerticalAlignment = .center
}
}/this is one of the things I tried, but whit this I get only the second image and its set in the center not right and the left image is hot even there/
UIButton has only one imageView, you can create custom button like in this answer
https://stackoverflow.com/a/43112735/13628690
Found the next solution: Made a custom UIView and added two images and label as a subview of customView. Did the constraints programaticly. Just added UITapGestureRecognizer (addGestureRecognizer) at the entire view and its all elements are clickable. The design and functionality are satisfied.

Easiest way to setup custom NavigationBar in Swift?

What is the easiest way to setup a custom NavigationBar in iOS/Swift?
I want to use a label above the navigation buttons (increased height). Is the only way to replace and hide the default NavigationBar and use an UIView?
(There's some missing things in your question, so this may not answer it.)
A UINavigationBar is simply a subclass of UIView, just as a UINavigationController is a subclass of a UIViewController. Where the former is just a "view" with a title and left/right bar buttons, the latter will have that and can also "control" a UIViewController stack.
Here's code for the former.
First, let's declare a label for the user name and a navigation bar with no title and a single left/right bar button. You can have an array of bar buttons on the left/right if you want. Also, I like to have SF Symbols with descriptive text, so I'll make UIButtons first.
let userName = UILabel()
let navBar = UINavigationBar()
let navItems = UINavigationItem(title: "")
var btnLeft:UIButton()
var btnRight:UIButton()
var barBtnLeft:UIBarButtonItem!
var barBtnRight:UIBarButtonItem!
Now let's populate things and set things up for auto layout. This all can be done during viewDidLoad, and change things (like user name) in other places.
// user name label
userName.translatesAutoresizingMaskIntoConstraints = false
userName.text = "User Name"
userName.textAlignment = .center
// create UIButtons with an SF Symbol and description
btnLeft.translatesAutoresizingMaskIntoConstraints = false
btnLeft.setImage(UIImage(systemName: "lessthan"), for: .normal)
btnLeft.setTitle(" left", for: .normal)
btnLeft.setTitleColor(.blue, for: .normal)
btnRight.translatesAutoresizingMaskIntoConstraints = false
btnRight.setImage(UIImage(systemName: "greaterthan"), for: .normal)
btnRight.setTitle(" right", for: .normal)
btnRight.setTitleColor(.blue, for: .normal)
// I like to "frame" these buttons, this is optional
btnLeft.layer.borderWidth = 1
btnLeft.layer.borderColor = UIColor.blue.cgColor
btnLeft.layer.cornerRadius = 5
btnRight.layer.borderWidth = 1
btnRight.layer.borderColor = UIColor.blue.cgColor
btnRight.layer.cornerRadius = 5
// now give the buttons a size
btnLeft.heightAnchor.constraint(equalToConstant: 44).isActive = true
btnLeft.widthAnchor.constraint(equalToConstant: 100).isActive = true
btnRight.heightAnchor.constraint(equalToConstant: 44).isActive = true
btnRight.widthAnchor.constraint(equalToConstant: 100).isActive = true
// don't forget to add targets!
btnLeft.addTarget(self, action: #selector(leftButtonSelector), for: .touchUpInside)
btnRight.addTarget(self, action: #selector(rightButtonSelector), for: .touchUpInside)
// make the result be a bar button
barBtnLeft = UIBarButtonItem(customView: btnLeft)
barBtnRight = UIBarButtonItem(customView: btnRight)
// add them to the navigation bar
navItems.leftBarButtonItems = [barBtnLeft]
navItems.rightBarButtonItems = [barBtnRight]
navBar.setItems([navItems], animated: false)
navBar.translatesAutoresizingMaskIntoConstraints = false
// add the label and navigation bar to your view
view.addSubview(userName)
view.addSubview(navBar)
// finally, lay the user name above the navigation bar
userName.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
userName.heightAnchor.constraint(equalToConstant: 44).isActive = true
userName.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
userName.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
navBar.topAnchor.constraint(equalTo: userName.bottomAnchor).isActive = true
navBar.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
navBar.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true

How to programmatically add tags to a UIButton in Swift

I know how to add tags in main.storyboard files, but now I am working on creating everything programmatically. However, I couldn't find anything online that tells me how to add tags to a button. I tried to read the apple documentation but don't know how to implement it.
Here is for example how I created my button, how can I add a tag to it, so that when I make multiple buttons and want to link them to a single action I can know what button has been pressed?
let buttonOne() : UIButton {
let button = UIButton(type: .system)
button.backgroundColor = .red
return button
}()
Try this:
let buttonOne() : UIButton {
let button = UIButton(type: .system)
button.backgroundColor = .red
button.tag = 2
return button
}()
Declare The Button
let menuChooseButton = UIButton()
menuChooseButton.frame.origin.y = 0
menuChooseButton.frame.origin.x = xPosition
menuChooseButton.frame.size.width = subViewWidth
menuChooseButton.frame.size.height = subViewHeight
menuChooseButton.backgroundColor = .clear
menuChooseButton.setTitle("", for: .normal)
menuChooseButton.tag = i
menuChooseButton.addTarget(self, action: #selector(menuSelectAction), for: .touchUpInside)
menuScrollView.addSubview(menuChooseButton)
Define Button Action
#objc func menuSelectAction(sender: UIButton!){
var tagNo: Int = sender.tag
if tagNo == 0{
// Whatever you want
}
}

Changing colour on buttons in tableview cell edit actions

Hello!
Having a go at swipe-to-delete functions and the likes in tableView cells today...
When toggling a button I would like it to change colours from green to red and back again. - Any suggestions on how to achieve this?
For the toggle button I have declared a boolean which is set
to false at start.
and this is what I've got inside editActionsForRowAtIndexPath:
...
let toggleAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "Toggle", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
let button: UIButton = UIButton()
button.backgroundColor = UIColor.greenColor()
if(self.toggleBool == false) {
self.toggleBool = true
button.backgroundColor = UIColor.redColor()
} else {
self.toggleBool = false
toggleButton.backgroundColor = UIColor.greenColor()
}
self.view.addSubview(button)
})
return [deleteAction, toggleAction]
}
The code snippet above does not make the button change colour when pressed!
Any help in the matter would be much appreciated!

Swift UIButton not appearing on screen

I have a view in my tabbar controller where I would like to show a button. I create this button programmatically based of a condition, therefore I use the following code but nothing is appearing:
override func viewDidLoad() {
super.viewDidLoad()
if !Settings.getIsConnected() {
notConnected()
}
}
func notConnected() {
let connectBtn = UIButton(frame: CGRect(x: self.view.center.x, y: self.view.center.y, width: 200, height: 45))
connectBtn.setTitle("Connect", forState: .Normal)
connectBtn.addTarget(self, action:#selector(self.pressedConnect(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(connectBtn)
print("Button created")
}
func pressedConnect(sender: UIButton!) {
}
I am clueless on what I am doing wrong. Anyone got suggestions? Cause it does print out "Button created" so it definitely runs the code inside the noConnected() method.
Add a background color to your UIButton and add a tint color to the title. This will resolve the problem
Try moving the code to viewDidAppear and see if the button is showing up.
The frame is not correctly set when in viewDidLoad. Use the method viewDidLayoutSubviews for the earliest possible time where the frame is correctly setup for a ViewController.
With this code change, you will need some additional logic for when your button should be added as a subview though.
A programmatically created button may not show up because of more reasons, e.g:
the tint color is not set
the background color is not set
the button is not added to the view hierarchy
the button is hidden
In your case, you should change the tint color or the background color of your button.
E.g.:
Swift 4.2:
private lazy var connectButton: UIButton = {
let button = UIButton(type: .custom)
button.backgroundColor = .green
button.setTitleColor(.black, for: .normal)
button.setTitle(NSLocalizedString("Connect", comment: ""), for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(connectButton)
}
You can re-check the button properties in the storyboard that it is not hidden.