Get rid of subview if collection view is empty - ios

I have a collection view when I display a message to the user if the collection view is empty. I also programmatically add a button to let the user add a photo if the collection view is empty. However, once the photo is added and the I reload the collection view, I found a way to get rid of the label, however, how can I get rid of the button's subview? since I can't access "self.collectionViews?.addSubview(button)" since it is in a guard let statement. Thanks in advance!
guard let parseUSERS = parseJSON["users"] as? [AnyObject] else {
// if the collection view is empty, display a message
let messageLabel = UILabel(frame: CGRect(x: 20.0, y: 10, width: self.collectionViews!.bounds.size.width - 40.0, height: (self.collectionViews?.bounds.size.height)!))
messageLabel.text = "Collection view is empty!"
messageLabel.font = messageLabel.font.withSize(20)
messageLabel.font = UIFont.boldSystemFont(ofSize: messageLabel.font.pointSize)
messageLabel.textColor = UIColor.white
messageLabel.numberOfLines = 0
messageLabel.textAlignment = NSTextAlignment.center
messageLabel.sizeToFit()
let button = UIButton(frame: CGRect(x: 80.0, y: 320, width: 215, height: 50))
button.backgroundColor = UIColor.white
button.setTitle("create",for: .normal)
button.setTitleColor(colorCircleBlue, for: .normal)
button.addTarget(self, action: #selector(self.action(sender:)), for: .touchUpInside)
// round corners for login/register buttons
button.layer.cornerRadius = button.bounds.width / 20
self.collectionViews?.backgroundColor = UIColor.blue
self.collectionViews?.backgroundView = messageLabel
self.collectionViews?.addSubview(button)
return
}
self.collectionViews?.backgroundColor = UIColor.white
self.collectionViews?.backgroundView = nil

I would recommend making a UIView that contains both your UILabel and the UIButton. Then setting the aforementioned UIView as the backgroundView of the UICollectionView. Ensure userInteraction is enabled on the backgroundView.
This will make sure that the both the UILabel & the UIButton are removed when you set the backgroundView to nil.
Something like this should do the trick (Be aware I have not tested this):
//Container view
let view = UIView.init(frame: self.collectionViews?.frame)
//Label
let messageLabel = UILabel(frame: CGRect(x: 20.0, y: 10, width: self.collectionViews!.bounds.size.width - 40.0, height: (self.collectionViews?.bounds.size.height)!))
messageLabel.text = "Collection view is empty!"
messageLabel.font = messageLabel.font.withSize(20)
messageLabel.font = UIFont.boldSystemFont(ofSize: messageLabel.font.pointSize)
messageLabel.textColor = UIColor.white
messageLabel.numberOfLines = 0
messageLabel.textAlignment = NSTextAlignment.center
messageLabel.sizeToFit()
//Button
let button = UIButton(frame: CGRect(x: 80.0, y: 320, width: 215, height: 50))
button.backgroundColor = UIColor.white
button.setTitle("create",for: .normal)
button.setTitleColor(colorCircleBlue, for: .normal)
button.addTarget(self, action: #selector(self.action(sender:)), for: .touchUpInside)
// round corners for login/register buttons
button.layer.cornerRadius = button.bounds.width / 20
//Add elements to container view
view.addSubview(messageLabel)
view.addSubview(button)
self.collectionViews?.backgroundView = view
Then in the future when you want to remove both elements you can just set the backgroundView to nil.

Related

button does not work after adding uiview in swift 4

let SearchView = UIView()
SearchView.backgroundColor = UIColor.clear
SearchView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
let Searchbutton = UIButton(type: .system)
Searchbutton.setImage(UIImage (named: "SEARCH"), for: .normal)
Searchbutton.backgroundColor = .clear
Searchbutton.frame = CGRect(x: -17, y: -20, width: 30, height: 30)
Searchbutton.contentMode = .scaleAspectFit
let WidthConstraint = Searchbutton.widthAnchor.constraint(equalToConstant: 30)
let HeightConstraint = Searchbutton.heightAnchor.constraint(equalToConstant: 30)
WidthConstraint.isActive = true
HeightConstraint.isActive = true
let barButtonItem = UIBarButtonItem(customView: SearchView)
self.navigationItem.rightBarButtonItem = barButtonItem
SearchView.addSubview(Searchbutton)
Searchbutton.addTarget(self, action: #selector(viewanewcontroller(button:)), for: .touchUpInside)
//right search button
After making a button, I wanted to move it little bit to the right. So, i made UI View to move the button inside the view. But, then, after this, the button does not work anymore. Can anyone tell me the solution?
Your code is working fine but need to clarify some points.
Reason Your button not working is below 4 lines
let WidthConstraint = Searchbutton.widthAnchor.constraint(equalToConstant: 30)
let HeightConstraint = Searchbutton.heightAnchor.constraint(equalToConstant: 30)
WidthConstraint.isActive = true
HeightConstraint.isActive = true
As you already set UIButton frame then no need to use of above lines of code.
Yellow color view is your SearchView and green color is your UIButton.
If you use Searchbutton frame like Searchbutton.frame = CGRect(x: -17, y: -20, width: 30, height: 30) then it happens something like below image.
You added UIButton as subview of UIView and when you click on green button which is inside yellow View will work but the area which is outside Yellow area doesn't work.
You need to start UIButton frame from 0,0,30,30
Searchbutton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
or you can directly set UIButton frame same as UIView frame then it looks like below image.
Searchbutton.frame = SearchView.frame
Below is your Working Code.
let SearchView = UIView()
SearchView.backgroundColor = UIColor.clear
SearchView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
let Searchbutton = UIButton(type: .system)
Searchbutton.setImage(UIImage (named: "SEARCH"), for: .normal)
Searchbutton.backgroundColor = .clear
Searchbutton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
Searchbutton.contentMode = .scaleAspectFit
let barButtonItem = UIBarButtonItem(customView: SearchView)
self.navigationItem.rightBarButtonItem = barButtonItem
SearchView.addSubview(Searchbutton)
Searchbutton.addTarget(self, action: #selector(viewanewcontroller(button:)), for: .touchUpInside)
//right search button
You're doing a lot of unnecessary things here. Firstly, you don't need to put your Button in a container view to put it as the right bar button item.
You also don't need to add constraints to your searchbutton, since you have given it a fixed frame.
let Searchbutton = UIButton(type: .system)
Searchbutton.setImage(UIImage (named: "SEARCH"), for: .normal)
Searchbutton.backgroundColor = .clear
Searchbutton.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
Searchbutton.contentMode = .scaleAspectFit
let barButtonItem = UIBarButtonItem(customView: Searchbutton)
self.navigationItem.rightBarButtonItem = barButtonItem
Searchbutton.addTarget(self, action: #selector(viewanewcontroller(button:)), for: .touchUpInside)
Also as Pratik's comment said, you're meant to use lower camel case. so SearchView should be searchView and SearchButton as searchButton
As for moving it to the right, it seems like that isn't possible anymore without either subclassing the UINavigationBar and changing the implementation, or by making UIViews look exactly like the standard Navigation Bar.
Get rid of the space on the right side of a UINavigationBar

datePicker is not showing on desired place

i have created my custom datepicker view and added UIdatePicker and two buttons in it.
both buttons are on the right place as desired but date picker is not showing on its right place
in image Red area is datepicker
here is my code for datepicker:
#objc func datePicker(){
//DatepickerView
self.datePickerView.frame = CGRect(x: 5, y: Int(SCREEN_HEIGHT-280), width: Int(SCREEN_WIDTH-10), height: 276)
self.datePickerView.backgroundColor = UIColor.white
self.datePickerView.layer.cornerRadius = 8.0
self.datePickerView.layer.masksToBounds = true
self.datePickerView.layer.borderWidth = 2;
self.datePickerView.layer.borderColor = UIColor.black.cgColor;
doneBtn.addTarget(self, action: #selector(doneClicked), for: .touchUpInside)
doneBtn.setTitle("Done", for: .normal)
doneBtn.frame = CGRect(x: 20, y: 10, width: 80, height: 50)
doneBtn.setTitleColor(UIColor.white, for: .normal)
doneBtn.backgroundColor = UIColor.black
doneBtn.titleLabel?.font = UIFont(name: "Montserrat-Regular", size:
16.0)
doneBtn.layer.cornerRadius = 16.0
doneBtn.layer.masksToBounds = true
doneBtn.layer.borderColor = UIColor.clear.cgColor
doneBtn.layer.borderWidth = 1
cancelBtn.addTarget(self, action:#selector(cancelClicked), for: .touchUpInside)
cancelBtn.setTitle("Cancel",for: .normal)
cancelBtn.frame = CGRect(x: SCREEN_WIDTH-110, y: 10, width: 80, height: 50)
cancelBtn.setTitleColor(UIColor.white, for: .normal)
cancelBtn.backgroundColor = UIColor.black
cancelBtn.titleLabel?.font = UIFont(name: "Montserrat-Regular", size: 16.0)
cancelBtn.layer.cornerRadius = 16.0
cancelBtn.layer.masksToBounds = true
cancelBtn.layer.borderColor = UIColor.clear.cgColor
cancelBtn.layer.borderWidth = 1
// DatePicker
self.datePicker = UIDatePicker(frame:CGRect(x: 0, y: 0, width: Int(SCREEN_WIDTH-20), height: 200))
self.datePicker?.backgroundColor = UIColor.red
self.datePicker?.datePickerMode = UIDatePickerMode.date
self.datePicker?.layer.masksToBounds = true
datePicker.center = view.center
datePickerView.addSubview(datePicker)
datePickerView.addSubview(doneBtn)
datePickerView.addSubview(cancelBtn)
self.view.addSubview(datePickerView)
datePickerView.isHidden = true;
}
i have tried more than 10 answers in stackoverflow, but did not worked for me.
Any idea why it is not appearing on right place
This was an iOS 14 problem that I ran into and my datePicker was only peeking out from the bottom of the screen. I found the answer here from PetterBraka:
if #available(iOS 14, *) {
datePicker.preferredDatePickerStyle = .wheels
datePicker.sizeToFit()
}
yourTextField.inputView = datePicker
What exactly you are trying to achieve ?
According to your code :
// DatePicker
self.datePicker = UIDatePicker(frame:CGRect(x: 0, y: 0, width: Int(SCREEN_WIDTH-20), height: 200))
self.datePicker?.backgroundColor = UIColor.red
self.datePicker?.datePickerMode = UIDatePickerMode.date
self.datePicker?.layer.masksToBounds = true
datePicker.center = view.center
you are setting datePicker frame according to the view self.datePickerView and adding as subView to it. But at the same time you are adding:
datePicker.center = view.center
according to the main view which has self.datePickerView as subview.
datePicker is out of the scope in that scenario.
Also your datePicker y frame can not be 0. It will overlap done and cancel button.
Hope this will helps:
I have commented datepicker center alignment code:
// DatePicker
self.datePicker = UIDatePicker(frame:CGRect(x: Int(self.doneBtn.frame.origin.x) , y: Int(doneBtn.frame.origin.y + doneBtn.frame.size.height + 10), width: Int(cancelBtn.frame.origin.x + cancelBtn.frame.size.width - self.doneBtn.frame.origin.x), height: 200))
self.datePicker.backgroundColor = UIColor.red
self.datePicker.datePickerMode = UIDatePickerMode.date
self.datePicker.layer.masksToBounds = true
// datePicker.center = view.center

how to customize a button's size in swift 3?

I want to resize a button as a square and here's my code:
let button = UIButton()
button.backgroundColor = UIColor.red
button.translatesAutoresizingMaskIntoConstraints = false
//method one
//button.widthAnchor.constraint(equalToConstant:44.0).isActive = true
//button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
//method two
button.frame.size = CGSize(width: 20.0, height: 20.0)
button.addTarget(self, action: #selector(ratingButtonTapped(button: )), for: .touchUpInside)
addArrangedSubview(button)
I have tried both method however none of them seem to work out fine with an error showing some mistakes in method one and nothing shown in method two. when i run the code, button is fulfilled in the container. what is wrong here?
Use addSubview() instead of addArrangedSubview().
I write here the playground with the same solution I posted in comments, in case someone encounters the same problem:
Swift 3.0:
//: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 400))
view.backgroundColor = UIColor.blue
let button = UIButton()
button.backgroundColor = UIColor.red
button.frame.size = CGSize(width: 40.0, height: 20.0)
button.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(button) // This does the trick
PlaygroundPage.current.liveView = view
Why not create the button and initialise it with the given size?
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
And then change the x and y accordingly

image and text for nav bar button item. swift

I saw the answer for this question for adding an image to the left nav bar item. And I did it successfully.
But I also want to add a small text next to the image. For example I want to show how many coins the user have. So I need to show a coins image and the number of coins next to it. How can it be done?
I tried to set title (with "123"), but I only see the image and not the title. This my code:
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "coins.png"), for: UIControlState.normal)
button.addTarget(self, action:#selector(self.callMethod), for: UIControlEvents.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
button.setTitle("123", for: UIControlState.normal)
let barButton = UIBarButtonItem.init(customView: button)
self.navigationItem.leftBarButtonItem = barButton
Thanks.
Since the bar button item is initialized with a custom view, you can add a UIImage and a UILabel to one view, along with a UIButton to capture the touch event, and pass that into the initializer.
// the UIButton is simply there to capture touch up event on the entire bar button view.
let button = UIButton.init(type: .custom)
button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
imageView.image = UIImage(named: "coins")
let label = UILabel(frame: CGRect(x: 35, y: 0, width: 50, height: 30))
label.text = "1234"
let buttonView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 30))
button.frame = buttonView.frame
buttonView.addSubview(button)
buttonView.addSubview(imageView)
buttonView.addSubview(label)
let barButton = UIBarButtonItem.init(customView: buttonView)
self.navigationItem.leftBarButtonItem = barButton
You might have to adjust the frames accordingly for your own uses, of course.
I think your problem is the width it's 30 try to make it bigger like 50
let buttonContainer:UIView = UIView()
buttonContainer.frame = CGRect(x: 0, y: 0, width: 50, height: 32)
let image = UIImage(named: "coins")
let button = UIButton.init(type: .system)
button.setImage(image, for: .normal)
button.frame = buttonContainer.frame
button.setTitle("sss", for: .normal)
button.addTarget(self, action: #selector(action(_:)), for: .touchUpInside)
buttonContainer.addSubview(button)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: buttonContainer)
You can use backgroundImage for image and setTitle for test to the button.
follow this link definitely you will get idea:
image for nav bar button item swift
Use self.navigationItem.leftBarButtonItems that is an array of UIBarButtonItem
let button = UIBarButtonItem()
let text = UIBarButtonItem()
self.navigationItem.leftBarButtonItems = [button, text]

Initialize a button with a title from a Label in swift

I want to initialize a button's title from a Label. I have this code:
let smallSquare = CGSize(width: 30, height: 30)
let button = UIButton(frame: CGRect(origin: CGPointZero, size: smallSquare))
But, I do not know how I can initialize a title with my label:
let label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "I'am a test label"
Normally, I use this property to add a title with a string:
button.setTitle("Button Title",for: .normal)
Is it possible to simply put my Label in my button's title?
Thanks in advance
You can add you custom label as subview to your button like Mike Alter mentioned in the comments like this (Note: Code is in Swift 3, but should be easy to adopt to Swift 2.*. Hints are in the code comments):
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let smallSquare = CGSize(width: 30, height: 30)
let button = UIButton(frame: CGRect(origin: .zero, size: smallSquare))
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .red
// add the button to your view
view.addSubview(button)
// set constraints of your button
button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.translatesAutoresizingMaskIntoConstraints = false
label.center = CGPoint(x: 160, y: 284)
label.textAlignment = .center
label.text = "I'm a test label"
// add the label to your button
button.addSubview(label)
// set constraints of your label
label.centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: button.centerYAnchor).isActive = true
}
}
Result with your custom values looks like this (Just added the red background of the button so you see the frame of the button compared to the label frame):
Your label has a text property. You used it to set a value and you can also use it to get the value. The text is optional, so you need to unwrap.
let labelText = label.text ?? ""
button.setTitle(labelText, for: .normal)
if let textFromLabel = yourCustomLabel.text {
yourButton.setTitle(textFromLabel, .normal)
}
is what I'll suggest you to do

Resources