Segue to different categories from Collection View - swift

Edit: I am on the right track, but the button can only point to 1 ViewController
I used
#IBAction func viewTouchedBttn(_ sender: Any) {
print("touched")
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
print("1")
performSegue(withIdentifier: "1", sender: nil)
case 1:
performSegue(withIdentifier: "2", sender: nil)
case 2:
performSegue(withIdentifier: "3", sender: nil)
default:
break
}
}
I recently done the tutorial about building a carousel in swift with a UICollectionView as taught in this tutorial https://www.youtube.com/watch?v=vB-HKnhOgl8 ( you can download it as well so we would have the same basis)
I am quit new to coding so I am sorry if this is quit obvious for you and I don't get it ^^.
Each category should point to a different vc by clicking on the cell.
When I press on the View with "Travel the world" the segue should point to the VC where you can talk about Travel, if I am interested in building apps and click on that view, I want to be directed to this specific category.
Thanks for your help! :)
edit: files
InterestCollectionView
class InterestCollectionViewCell: UICollectionViewCell
{
#IBOutlet weak var featuredImageView: UIImageView!
#IBOutlet weak var interestTitleLabel: UILabel!
#IBOutlet weak var backgroundColorView: UIView!
#IBOutlet weak var kategorie: UILabel!
var interest: Interest? {
didSet {
self.updateUI()
}
}
private func updateUI()
{
if let interest = interest {
kategorie.text = interest.kategorie
featuredImageView.image = interest.featuredImage
interestTitleLabel.text = interest.title
backgroundColorView.backgroundColor = interest.color
} else {
featuredImageView.image = nil
interestTitleLabel.text = nil
backgroundColorView.backgroundColor = nil
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = 3.0
layer.shadowRadius = 10
layer.shadowOpacity = 0.4
layer.shadowOffset = CGSize(width: 5, height: 10)
self.clipsToBounds = false
}
}
interest file
class Interest
{
// MARK: - Public API
var kategorie = ""
var title = ""
var featuredImage: UIImage
var color: UIColor
init(title: String, featuredImage: UIImage, color: UIColor, kategorie: String)
{
self.kategorie = kategorie
self.title = title
self.featuredImage = featuredImage
self.color = color
}
// MARK: - Private
// dummy data
static func fetchInterests() -> [Interest]
{
return [
Interest(title: "Travelling Around the World", featuredImage: UIImage(named: "f1")!, color: UIColor(red: 63/255.0, green: 71/255.0, blue: 80/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "Cafe with Best Friends", featuredImage: UIImage(named: "f2")!, color: UIColor(red: 240/255.0, green: 133/255.0, blue: 91/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "Study Personal Development Books and Courses", featuredImage: UIImage(named: "f3")!, color: UIColor(red: 105/255.0, green: 80/255.0, blue: 227/255.0, alpha: 0.8), kategorie: "Post"),
Interest(title: "Build Amazing iOS Apps", featuredImage: UIImage(named: "f4")!, color: UIColor(red: 102/255.0, green: 102/255.0, blue: 102/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "Learn. Create. Contribute.", featuredImage: UIImage(named: "f5")!, color: UIColor(red: 245/255.0, green: 62/255.0, blue: 40/255.0, alpha: 0.8),kategorie: "Forum"),
Interest(title: "Inspire, Instruct, and Empower People", featuredImage: UIImage(named: "f6")!, color: UIColor(red: 103/255.0, green: 217/255.0, blue: 87/255.0, alpha: 0.8), kategorie: "Bilder"),
Interest(title: "Business and Marketing Geeks", featuredImage: UIImage(named: "f7")!, color: UIColor(red: 63/255.0, green: 71/255.0, blue: 80/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "3D Printing, Virtual Reality and AI", featuredImage: UIImage(named: "f8")!, color: UIColor(red: 240/255.0, green: 133/255.0, blue: 91/255.0, alpha: 0.8), kategorie: "Forum"),
Interest(title: "Einzeiler", featuredImage: UIImage(named: "f3")!, color: UIColor(red: 30/255.0, green: 20/255.0, blue: 130/255.0, alpha: 0.8), kategorie: "Forum")
]
}
}
the interest ViewController
import UIKit
class InterestsViewController: UIViewController
{
#IBOutlet weak var collectionView: UICollectionView!
var interests = Interest.fetchInterests()
let cellScaling: CGFloat = 0.6
override func viewDidLoad() {
super.viewDidLoad()
let screenSize = UIScreen.main.bounds.size
let cellWidth = floor(screenSize.width * cellScaling)
let cellHeight = floor(screenSize.height * cellScaling)
let insetX = (view.bounds.width - cellWidth) / 2.0
let insetY = (view.bounds.height - cellHeight) / 2.0
let layout = collectionView!.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: cellWidth, height: cellHeight)
collectionView?.contentInset = UIEdgeInsets(top: insetY, left: insetX, bottom: insetY, right: insetX)
collectionView?.dataSource = self
collectionView?.delegate = self
}
}
extension InterestsViewController : UICollectionViewDataSource
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return interests.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InterestCell", for: indexPath) as! InterestCollectionViewCell
cell.interest = interests[indexPath.item]
return cell
}
}
extension InterestsViewController : UIScrollViewDelegate, UICollectionViewDelegate
{
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
{
let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing
var offset = targetContentOffset.pointee
let index = (offset.x + scrollView.contentInset.left) / cellWidthIncludingSpacing
let roundedIndex = round(index)
offset = CGPoint(x: roundedIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
targetContentOffset.pointee = offset
}
}

You have multiple options to do what you want.
For example you could add in your storyboard a storyboard reference to controller you want to segue to, or a view controller if it's in the same storyboard. And then ctrl + drag from the view to the view controller (or storyboard reference) that you want to segue to. There you will have the different segues types (show, push, etc).
That's the full storyboard way of doing it.
There are multiple other options. But that may be the easiest.
https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/UsingSegues.html
EDIT:
You can also create 8 segues from the controller (ctrl + drag from controller) to other controllers or storyboard references. Then click on the segues created and in the identifier inspector name every segue with a unique identifier.
Then when you click on the cell you can determine which cell was clicked and perform the segue you need for that cell with performSegueWithIdentifier(identifier, sender)

Related

Problem with background in table when emulating Iphone Max Pro 12

I'm trying to emulate my app in different Iphone models but I'm also having the same mistake when I use a Max Pro 12. Anytime I use a tableViewContoller it seems not to fill the background cells completely. Just check my pictures. In the rest of models, including Max Pro 11 it's working ok. I don`t have any constraints because the I can't add them when I use tableViewController. Any suggestion?
Here you have my code.
import UIKit
import FirebaseAuth
class MenuCustomCellController: UITableViewCell {
#IBOutlet weak var imEvento: UIImageView!
#IBOutlet weak var txtNombreEvento: UILabel!
#IBOutlet weak var txtFechaEvento: UILabel!
#IBOutlet weak var txtEstadoEvento: UILabel!
}
class MenuInicialTableController: UITableViewController {
#IBOutlet weak var celdaUsuarios: UITableViewCell!
#IBOutlet weak var celdaEventos: UITableViewCell!
#IBOutlet weak var celdaBuscarEventos: UITableViewCell!
#IBOutlet weak var celdaGraficos: UITableViewCell!
#IBOutlet weak var celdaCerrar: UITableViewCell!
#IBOutlet weak var celdaAyuda: UITableViewCell!
override func viewWillAppear(_ animated: Bool) {
let tap = UITapGestureRecognizer(target: self, action: #selector(MenuInicialTableController.tapFunction))
celdaCerrar.isUserInteractionEnabled = true
celdaCerrar.addGestureRecognizer(tap)
let background = UIView()
tableView.backgroundView = background
tableView.backgroundView?.aplicarFondoDegradado()
tableView.layer.borderWidth = 2
tableView.layer.borderColor = UIColor.white.cgColor
tableView.layer.cornerRadius = 10
celdaUsuarios.layer.borderWidth = 1
celdaUsuarios.layer.borderColor = UIColor.white.cgColor
celdaUsuarios.layer.cornerRadius = 10
celdaUsuarios.contentView.aplicarFondoMenuUsuarios()
celdaEventos.layer.borderWidth = 1
celdaEventos.layer.borderColor = UIColor.white.cgColor
celdaEventos.layer.cornerRadius = 10
celdaEventos.contentView.aplicarFondoMenuEventos()
celdaGraficos.layer.borderWidth = 1
celdaGraficos.layer.borderColor = UIColor.white.cgColor
celdaGraficos.layer.cornerRadius = 10
celdaGraficos.contentView.aplicarFondoMenuEventos()
celdaCerrar.layer.borderWidth = 1
celdaCerrar.layer.borderColor = UIColor.white.cgColor
celdaCerrar.layer.cornerRadius = 10
celdaCerrar.contentView.aplicarFondoMenuUsuarios()
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "MENÚ PRINCIPAL"
self.navigationItem.setHidesBackButton(true, animated: true)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
//Dos filas por sección
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
#objc
func tapFunction(sender:UITapGestureRecognizer) {
exit(0)
}
}
And here you have how I apply gradients:
func aplicarFondoMenuUsuarios() {
let colorInicio = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).cgColor
let colorFin = UIColor(red: 0/255, green: 190/255, blue: 219/255, alpha: 1.0).cgColor
if let gradientLayer = layer.sublayers?.first as? CAGradientLayer {
gradientLayer.colors = [colorInicio,colorFin]
}
else{
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorInicio, colorFin]
gradientLayer.startPoint = CGPoint(x: 0, y: 0.50)
gradientLayer.endPoint = CGPoint(x: 0.50, y: 1.00)
gradientLayer.frame = self.bounds
self.layer.insertSublayer(gradientLayer, at:0)
}
func aplicarFondoMenuEventos() {
let colorInicio = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).cgColor
let colorFin = UIColor(red: 15/255, green: 0/255, blue: 219/255, alpha: 1.0).cgColor
if let gradientLayer = layer.sublayers?.first as? CAGradientLayer {
gradientLayer.colors = [colorInicio,colorFin]
}
else{
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorInicio, colorFin]
gradientLayer.startPoint = CGPoint(x: 0, y: 0.50)
gradientLayer.endPoint = CGPoint(x: 0.50, y: 1.00)
gradientLayer.frame = self.bounds
self.layer.insertSublayer(gradientLayer, at:0)
}
}
Don't use viewWillAppear for layout-code. And not for TapGestures either. Move the three first lines (tap-related) into viewDidLoad, and put the rest into override func viewDidLayoutSubviews(){}.
There are a lot of other stuff you should do as well, like subclassing the cells and have them perform their gradients at the time of their own layout, and you should also remove let background = UIView() and instead just say tableView.backgroundView = UIView() in viewDidLoad (not in willAppear and not in viewDidLayoutSubviews).

collectionView Animates Color on Reload

Whenever collectionView reloads, firstColor and secondColor mixes for a moment then get back to how they should be. For some reason adding gradient caused that problem. without gradient and with only one color this problem does not occur.
Here is the video link to the problem. Video
extension PostSurveyViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.surveyColors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SurveyColorCollectionViewCell.identifier, for: indexPath) as? SurveyColorCollectionViewCell
cell!.setup(surveyViewModel.surveyColors[indexPath.row])
return cell!
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.allowsMultipleSelection = false
for index in surveyViewModel.surveyColors.indices {
self.surveyViewModel.surveyColors[index].isSelected = false
}
self.surveyViewModel.surveyColors[indexPath.row].isSelected = true
self.collectionView.reloadData()
}
}
class SurveyColorCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var bigSquare: UIView!
let gradientLayer: CAGradientLayer = CAGradientLayer()
static let identifier = String(describing: SurveyColorCollectionViewCell.self)
override func awakeFromNib() {
super.awakeFromNib()
}
func setupGradient(_ survey: SurveyModel) {
gradientLayer.frame = bigSquare.bounds
bigSquare.layer.insertSublayer(gradientLayer, at: 0)
let topColor: CGColor = survey.firstColor.cgColor
let bottomColor: CGColor = survey.secondColor.cgColor
gradientLayer.colors = [topColor, bottomColor]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
bigSquare.clipsToBounds = true
}
func setup(_ survey: SurveyModel) {
bigSquare.layer.borderWidth = 1
bigSquare.layer.borderColor = UIColor.systemGray.cgColor
bigSquare.layer.cornerRadius = 8
self.setupGradient(survey)
}
class SurveyViewModel {
var surveyColors: [SurveyModel] = []
func getSurveys() {
surveyColors = [
SurveyModel(firstColor: UIColor.white, secondColor: UIColor.white, isSelected: true),
SurveyModel(firstColor: UIColor(red: 255/255, green: 138/255, blue: 0/255, alpha: 1), secondColor: UIColor(red: 159/255, green: 0/255, blue: 73/255, alpha: 1), isSelected: false),
SurveyModel(firstColor: UIColor(red: 19/255, green: 146/255, blue: 299/255, alpha: 1), secondColor: UIColor(red: 123/255, green: 0/255, blue: 139/255, alpha: 1), isSelected: false),
SurveyModel(firstColor: UIColor(red: 68/255, green: 204/255, blue: 98/255, alpha: 1), secondColor: UIColor(red: 0/255, green: 88/255, blue: 139/255, alpha: 1), isSelected: false)
]
}
}
struct SurveyModel {
let firstColor: UIColor
let secondColor: UIColor
var isSelected: Bool
}

Make view with tableview as its subview a gradient color

I can make the view a background gradient without the tableview. When I add the tableview, I can either have the gradient view without the tableview cells visible or the tableview cells are visible with a white background. I cannot present the tableview with the cells visible and the gradient visible "underneath" it as the background.
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
setGradientBackground()
}
func setGradientBackground() {
let colorTop = UIColor(red: 83/255, green: 187/255, blue: 204/255, alpha: 1.0).cgColor
let colorBottom = UIColor(red: 64/255, green: 109/255, blue: 164/255, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorTop, colorBottom]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.frame = self.view.bounds
tableView.layer.insertSublayer(gradientLayer, at:0)
}
private func configureTableView() {
tableView.register(NavigationMenuTableViewCell.self, forCellReuseIdentifier: "menu")
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
view.addSubview(tableView)
tableView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
}
class NavigationMenuTableViewCell: UITableViewCell {
private let label = UILabel()
func setup(_ buttonName: String) {
label.text = buttonName
label.font = UIFont.systemFont(ofSize: 14)
label.layer.cornerRadius = 6
label.clipsToBounds = true
label.textColor = .white
label.textAlignment = .center
label.backgroundColor = UIColor.init(displayP3Red: 50/255, green: 96/255, blue: 149/255, alpha: 1)
contentView.addSubview(label)
label.frame = CGRect(x: 20, y: 3, width: contentView.frame.width - 40, height: contentView.frame.height - 6)
}
}
You should create a separate view and set it as backgroundView for tableView.
In my case with collectionView it helped.
final class ViewController: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
setGradientBackground()
}
private func setGradientBackground() {
let colorTop = UIColor(red: 83/255, green: 187/255, blue: 204/255, alpha: 1.0).cgColor
let colorBottom = UIColor(red: 64/255, green: 109/255, blue: 164/255, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorTop, colorBottom]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.frame = self.view.bounds
let backgroundView = UIView(frame: collectionView.bounds)
backgroundView.layer.insertSublayer(gradientLayer, at: .zero)
collectionView.backgroundView = backgroundView
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
cell.backgroundColor = .white
return cell
}
}
Result

Edit collectionView Cells in UICollectionView

I am creating an app programitcally (on my first try). I have managed to create a collection view and on the click of the add button in the navigation bar a new cell appears. I want to be able to set all cells created to be editable (in other words show the delete button on the cells) when the edit button in the navigation bar is clicked. Currently no matter what I try whether I click on edit or not, nothing happens. I have tried hiding the UIImage of the button as well as the button by calling a function created in the cell class when the edit button is clicked and have also tried moving this function to the ViewController Class, app runs but code doesn't do what it is supposed to.
My Code:
class CollectionViewController: UICollectionViewController, UITextViewDelegate {
// decelrations of variables for use
let cell = ListCell()
let cellId = "cellId"
var numberOfLists = 0
var lists = [String]()
let secondVC = TableViewController()
// for learning purposes: codes sets up the view programitcally along with what is in scenedelagate
override func viewDidLoad() {
super.viewDidLoad()
setCollectionView()
}
//Function that will generate the collectionView
func setCollectionView() {
collectionView.register(ListCell.self, forCellWithReuseIdentifier: cellId)
collectionView.backgroundColor = .white
navigationItem.title = "Lists"
navigationController?.navigationBar.barTintColor = UIColor(white: 200/255, alpha: 1)
navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white, .font: UIFont.boldSystemFont(ofSize: 20)]
navigationItem.leftBarButtonItem = editButtonItem
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
collectionView.delegate = self //runs the delegate flow methods
collectionView.dataSource = self
}
// to do with enabling editing in CV - function tied to edit button
override func setEditing(_ editing: Bool, animated: Bool){
super.setEditing(editing, animated: animated)
if editing {
print ("Editing Mode Enabled")
//cell.showButton()
} else {
print ("Editing Mode Closed")
}
// reloads the view after code is performed
self.collectionView.reloadData()
}
// func when buttons are tapped to add a collection view
#objc func addTapped() {
print("This button should not crash")
numberOfLists += 1
navigationController?.pushViewController(secondVC, animated: true)
collectionView.reloadData()
}
}
// the following block of code has to do with the set up of the collectionView
extension CollectionViewController: UICollectionViewDelegateFlowLayout {
// this code should speficiy how many cells you are going to have in your collectionview
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfLists
}
// this code lets you reuse a cell
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)-> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ListCell
cell.deleteButton.setImage(UIImage.init(named: "delete"), for: .normal)
return cell
}
// this code sets the sizing of the cells
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (view.frame.width / 2) - 16, height: 100)
}
// where to place the cell on the screen
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 8, left: 9, bottom: 8, right: 8)
}
// this function just checks to see if the cell is selected
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
navigationController?.pushViewController(secondVC, animated: true)
}
}
//this class sets up the collectionViewCell
class ListCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupCell()
}
fileprivate func setupCell(){
let colors = cellRandomBackgroundColors()
self.backgroundColor = colors[0]
self.addSubview(listNameLabel)
roundCorner()
setCellShadow()
self.addSubview(deleteButton)
deleteButton.addTarget(self, action: #selector(deleteCell), for: .touchUpInside)
}
#objc func deleteCell() {
print ("this button works")
}
func showButton() {
deleteButton.isHidden = true
print ("this is supposed to work")
}
func roundCorner() {
self.contentView.layer.cornerRadius = 50.0
self.contentView.layer.masksToBounds = true
self.contentView.layer.borderWidth = 1.0
self.contentView.layer.borderColor = UIColor.clear.cgColor
}
func setCellShadow() {
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 1)
self.layer.shadowOpacity = 0.2
self.layer.shadowRadius = 1.0
self.layer.masksToBounds = false
self.layer.cornerRadius = 3
self.clipsToBounds = false
}
func cellRandomBackgroundColors() -> [UIColor] {
//Colors
let red = [#colorLiteral(red: 0.9654200673, green: 0.1590853035, blue: 0.2688751221, alpha: 1),#colorLiteral(red: 0.7559037805, green: 0.1139892414, blue: 0.1577021778, alpha: 1)]
let orangeRed = [#colorLiteral(red: 0.9338900447, green: 0.4315618277, blue: 0.2564975619, alpha: 1),#colorLiteral(red: 0.8518816233, green: 0.1738803983, blue: 0.01849062555, alpha: 1)]
let orange = [#colorLiteral(red: 0.9953531623, green: 0.54947716, blue: 0.1281470656, alpha: 1),#colorLiteral(red: 0.9409626126, green: 0.7209432721, blue: 0.1315650344, alpha: 1)]
let yellow = [#colorLiteral(red: 0.9409626126, green: 0.7209432721, blue: 0.1315650344, alpha: 1),#colorLiteral(red: 0.8931249976, green: 0.5340107679, blue: 0.08877573162, alpha: 1)]
let green = [#colorLiteral(red: 0.3796315193, green: 0.7958304286, blue: 0.2592983842, alpha: 1),#colorLiteral(red: 0.2060100436, green: 0.6006633639, blue: 0.09944178909, alpha: 1)]
let greenBlue = [#colorLiteral(red: 0.2761503458, green: 0.824685812, blue: 0.7065336704, alpha: 1),#colorLiteral(red: 0, green: 0.6422213912, blue: 0.568986237, alpha: 1)]
let kindaBlue = [#colorLiteral(red: 0.2494148612, green: 0.8105323911, blue: 0.8425348401, alpha: 1),#colorLiteral(red: 0, green: 0.6073564887, blue: 0.7661359906, alpha: 1)]
let skyBlue = [#colorLiteral(red: 0.3045541644, green: 0.6749247313, blue: 0.9517192245, alpha: 1),#colorLiteral(red: 0.008423916064, green: 0.4699558616, blue: 0.882807076, alpha: 1)]
let blue = [#colorLiteral(red: 0.1774400771, green: 0.466574192, blue: 0.8732826114, alpha: 1),#colorLiteral(red: 0.00491155684, green: 0.287129879, blue: 0.7411141396, alpha: 1)]
let bluePurple = [#colorLiteral(red: 0.4613699913, green: 0.3118675947, blue: 0.8906354308, alpha: 1),#colorLiteral(red: 0.3018293083, green: 0.1458326578, blue: 0.7334778905, alpha: 1)]
let purple = [#colorLiteral(red: 0.7080290914, green: 0.3073516488, blue: 0.8653779626, alpha: 1),#colorLiteral(red: 0.5031493902, green: 0.1100070402, blue: 0.6790940762, alpha: 1)]
let pink = [#colorLiteral(red: 0.9495453238, green: 0.4185881019, blue: 0.6859942079, alpha: 1),#colorLiteral(red: 0.8123683333, green: 0.1657164991, blue: 0.5003474355, alpha: 1)]
let colorsTable: [Int: [UIColor]] = [0: red, 1: orangeRed, 2: orange, 3: yellow, 4: green, 5: greenBlue, 6: kindaBlue, 7: skyBlue, 8: blue, 9: bluePurple, 10: bluePurple, 11: purple, 12: pink]
let randomColors = colorsTable.values.randomElement()
return randomColors!
}
let deleteButton: UIButton = {
let deleteButton = UIButton(frame: CGRect(x:2,y:2,width:70,height:30))
return deleteButton
}()
let listNameLabel: UILabel = {
let listLabel = UILabel(frame: CGRect(x:2,y:50,width:70,height:30))
listLabel.text = "Data entry on Second View"
listLabel.font = UIFont.boldSystemFont(ofSize: 12)
listLabel.backgroundColor = .green
listLabel.translatesAutoresizingMaskIntoConstraints = false
listLabel.tag = 1
return listLabel
}()
let iconImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "Folder")
imageView.contentMode = .scaleAspectFit
return imageView
}()
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Edit Button on Cells that doesn't disappear

Creating a Custom Tab Bar

I want to create a custom tab bar at the top. Just like 9gag. Do you know a place where i can learn how to do it? (documentiation or video tutorial) Thanks
9gag custom tab bar
You can use a collection view to create something like this.
Here is how to do it:
Create your ViewController interface like shown in the screenshot below:
Don't forget to set the scroll direction of collection view to horizontal
2. Create the custom collection view cell class as
import UIKit
class CustomCollectionViewCell: UICollectionViewCell
{
//MARK: Outlets
#IBOutlet private weak var titleLabel: UILabel!
#IBOutlet private weak var blueDividerLineImageView: UIImageView!
//MARK: Overridden Properties
override var isSelected: Bool{
willSet{
super.isSelected = newValue
if newValue
{
self.titleLabel.textColor = UIColor(red: 0.0/255.0, green: 122.0/255.0, blue: 255.0/255.0, alpha: 1.0)
self.blueDividerLineImageView.isHidden = false
}
else
{
self.titleLabel.textColor = UIColor.black
self.blueDividerLineImageView.isHidden = true
}
}
}
//MARK: Internal Properties
var titleString : String?{
get{
return self.titleLabel.text
}
set{
self.titleLabel.text = newValue
}
}
//MARK: View Lifecycle Methods
override func awakeFromNib()
{
self.titleLabel.text = nil
}
}
3. Create your ViewController class as:
import UIKit
class ViewController: UIViewController
{
#IBOutlet weak var customCollectionView: UICollectionView!
let tabsArray = ["Tab 1", "Tab 2", "Tab 3", "Tab 4", "Tab 5"]
override func viewDidLoad()
{
}
override var prefersStatusBarHidden: Bool{
return true
}
}
// MARK: - UICollectionViewDataSource, UICollectionViewDelegate Methods
extension ViewController : UICollectionViewDataSource, UICollectionViewDelegate
{
//MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return self.tabsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCollectionViewCell", for: indexPath) as! CustomCollectionViewCell
cell.titleString = self.tabsArray[indexPath.row]
return cell
}
//MARK: UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath)
{
//For initially highlighting the first cell of "customCollectionView" when ViewController is loaded
guard let _ = collectionView.indexPathsForSelectedItems?.first, indexPath.row != 0 else
{
cell.isSelected = true
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .left)
return
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
print("\(self.tabsArray[indexPath.row]) Pressed")
//Do your task here..whatever you want to do when pressing the tabs
}
}
The output screen is:
A work around which I implemented.
Create a view to have the custom tab bar.
let tabView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 60))
tabView.backgroundColor = UIColor(red: 45/255, green: 58/255, blue: 114/255, alpha: 1)
self.view.addSubview(tabView)
Depending on the number of buttons, decide the button size and add them as subview.(Taking 2 here)
firstButton = UIButton(type: .Custom)
firstButton.frame = CGRect(x: 0, y: 20, width: tabView.frame.size.width / 2, height: 30)
firstButton.setTitle("BUT 1", forState: .Normal)
firstButton.setTitleColor(UIColor(red: 0/255, green: 191/255, blue: 165/255, alpha: 1.0), forState: .Normal)
firstButton.addTarget(self, action: #selector(ViewController.firstButtonTapped), forControlEvents: .TouchUpInside)
tabView.addSubview(firstButton)
secondButton = UIButton(type: .Custom)
secondButton.frame = CGRect(x: tabView.frame.size.width / 2, y: 20, width: tabView.frame.size.width / 2, height: 30)
secondButton.setTitle("BUT 2", forState: .Normal)
secondButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
secondButton.addTarget(self, action: #selector(ViewController.secondButtonTapped), forControlEvents: .TouchUpInside)
tabView.addSubview(secondButton)
Add a small UIView which serves as a line below the buttons.
lineView = UIView()
lineView.frame = CGRect(x: 0, y: CGRectGetMaxY(tabView.frame) - 3, width: tabView.frame.size.width / 2, height: 3)
lineView.backgroundColor = UIColor(red: 0/255, green: 191/255, blue: 165/255, alpha: 1.0)
tabView.addSubview(lineView)
Make the view below in a scrollview.
self.scrollView.frame = CGRectMake(0, CGRectGetMaxY(tabView.frame), self.view.frame.width, self.view.frame.height)
self.scrollView.backgroundColor = UIColor.whiteColor()
self.scrollView.delegate = self
self.scrollView.pagingEnabled = true
self.view.addSubview(self.scrollView)
let aScrollViewWidth = self.scrollView.frame.width
let aScrollViewHeight = self.scrollView.frame.height
self.scrollView.contentSize = CGSizeMake(aScrollViewWidth * CGFloat(2), aScrollViewHeight)
Add your views one after the other. For the sake of the example, I am just adding a UITextView.
for anIndex in 0 ..< 2 {
let anEssayTextView = UITextView(frame: CGRectMake(aScrollViewWidth * CGFloat(anIndex), 0, aScrollViewWidth, aScrollViewHeight))
anEssayTextView.text = essays[anIndex]
anEssayTextView.editable = false
self.scrollView.addSubview(anEssayTextView)
}
ScrollView delegate function
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
if (pageNumber == 0) {
firstButtonTapped()
} else {
secondButtonTapped()
}
}
Button actions
func firstButtonTapped() {
firstButton.setTitleColor(UIColor(red: 0/255, green: 191/255, blue: 165/255, alpha: 1.0), forState: .Normal)
secondButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
if (self.lineView.frame.origin.x != 0) {
UIView.animateWithDuration(0.25) {
self.lineView.frame.origin.x -= self.tabView.frame.size.width / 2
}
}
scrollView.setContentOffset(CGPointMake(0, 0), animated: true)
pageNumber = 0
}
func secondButtonTapped() {
firstButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
secondButton.setTitleColor(UIColor(red: 0/255, green: 191/255, blue: 165/255, alpha: 1.0), forState: .Normal)
if (self.lineView.frame.origin.x != self.tabView.frame.size.width / 2) {
UIView.animateWithDuration(0.25) {
self.lineView.frame.origin.x += self.tabView.frame.size.width / 2
}
}
scrollView.setContentOffset(CGPointMake(self.scrollView.frame.size.width, 0), animated: true)
pageNumber = 1
}