I would like to make a transition by placing a UITableView within the UINavigationController class and tapping the cell in it.
However, no matter how many times I press cell, it does not make a transition.
The code is the last one, "self.pushViewController (editViewController, animated: true)".
I am assuming navigationPush, but I would like you to tell me why it does not work.
I will ask for answers.
import UIKit
import APIKit
class BookListViewController: UINavigationController {
struct BookInfo {
let bookImage: UIImage?
let bookTitle: UILabel?
let bookPrice: UILabel?
let bookID: UILabel?
}
private lazy var navBar: UINavigationBar = {
let navBar = UINavigationBar()
navBar.frame = CGRect(x: 0, y: view.safeAreaInsets.top, width: view.frame.width, height: 44)
navBar.barTintColor = UIColor.white
let navItem = UINavigationItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(bookAdd))
navItem.rightBarButtonItem = addButton
navItem.title = "書籍一覧"
navBar.pushItem(navItem, animated: false)
return navBar
}()
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.frame = CGRect(x: 0, y: navigationBar.frame.size.height + view.safeAreaInsets.top, width: view.frame.size.width, height: view.frame.size.height - view.safeAreaInsets.bottom)
tableView.rowHeight = 100
tableView.delegate = self
tableView.dataSource = self
tableView.register(BookListCell.self, forCellReuseIdentifier: NSStringFromClass(BookListCell.self))
return tableView
}()
private lazy var safeView: UIView = {
let safeView = UIView()
safeView.backgroundColor = UIColor.white
safeView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.safeAreaInsets.top)
return safeView
}()
private lazy var loadButton: UIButton = {
let button = UIButton()
button.setTitle("読込", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
button.backgroundColor = UIColor.blue
button.layer.cornerRadius = 25
button.addTarget(self, action: #selector(moreLoad(sender:)), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
setupUI()
}
}
extension BookListViewController {
private func setupUI() {
view.addSubview(navBar)
view.addSubview(safeView)
view.addSubview(tableView)
view.addSubview(loadButton)
loadButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20.0).isActive = true
loadButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -100.0).isActive = true
loadButton.widthAnchor.constraint(equalToConstant: 50.0).isActive = true
loadButton.heightAnchor.constraint(equalToConstant: 50.0).isActive = true
}
#objc func bookAdd() {
let bookAddViewController = BookAddViewController()
self.present(bookAddViewController, animated: true)
}
#objc func moreLoad(sender: UIButton) {
print("moreLoad!!")
}
}
extension BookListViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell: BookListCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(BookListCell.self), for: indexPath) as? BookListCell {
cell.bookimage.image = UIImage(named: "hoge")
cell.title.text = "書籍一覧"
cell.price.text = "200.000円"
cell.bookDay.text = "2018/12/31"
cell.editButton.setTitle(">", for: .normal)
return cell
}
let cell = UITableViewCell()
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
//個別の情報を載せて遷移
let editViewController = R.storyboard.main.edit()!
self.pushViewController(editViewController, animated: true)
}
}
In storyboard you need to add navigation controller which make this controller as rootviewcontroller. Just by dragging from navigation controller to your tableview controller.
You should extend BookListViewController from UIViewController and present this controller from another controller like this self.present(UINavigationController(rootViewController: BookListViewController()), animated: true) then you can access navigationItem easily with self.navigationItem inside BookListViewController.
self show current context when we use self.navigationController then we are actually telling push to perform that push on that current view's navigation controller
use:
self.navigationController.pushViewController(editViewController, animated: true)
Related
I have a tableView, that is accessed via a sideMenu where this particular viewController is a child viewController.
For some reason, when I add the tableView.delegate = self, also tableView.dataSource
and register the cell. My app crashes. When I set this view Controller as the initial view controller the table view shows up, however when I return it to my home page, the app crashes, and does not want to load.
My IBOutlets are connected correctly. I even tried connecting the data source and delegate in storyboard.
I have added two types of code for you all to look at, the first, has an IBOutlet, the second I have tried an addSubView(table) however, no table appears.
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(table)
table.delegate = self
table.dataSource = self
table.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
Here is my Wallet View Controller
//
// WalletViewController.swift
// handlwithcare
//
// Created by Charles Morgan on 16/10/2021.
//
import UIKit
import RealmSwift
class WalletViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let button = UIButton()
#IBOutlet var table: UITableView!
private var data = [AddCardItem]()
override func viewDidLoad() {
super.viewDidLoad()
table.delegate = self
table.dataSource = self
table.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
view.backgroundColor = UIColor(named: "RED")
button.setTitle("Add New Card", for: .normal)
view.addSubview(button)
button.backgroundColor = UIColor(named: "yellow-2")
button.setTitleColor(UIColor(named: "RED"), for: .normal)
button.frame = CGRect(x: 50, y: 800, width: 350, height: 50)
button.layer.cornerRadius = 15
button.addTarget(self, action: #selector(didTapAddButton), for: .touchUpInside)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = data[indexPath.row].item
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
#objc private func didTapAddButton() {
let rootVC = addCardViewController()
let navVC = UINavigationController(rootViewController: rootVC)
navVC.modalPresentationStyle = .fullScreen
present(navVC, animated: true)
}
}
class AddCardItem: Object {
#objc dynamic var item: String = ""
#objc dynamic var date: Date = Date()
}
Here is my Second attempt with a view.addSubView
import UIKit
import RealmSwift
class WalletViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let button = UIButton()
let table = UITableView()
private var data = [AddCardItem]()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(table)
table.delegate = self
table.dataSource = self
table.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
view.backgroundColor = UIColor(named: "RED")
button.setTitle("Add New Card", for: .normal)
view.addSubview(button)
button.backgroundColor = UIColor(named: "yellow-2")
button.setTitleColor(UIColor(named: "RED"), for: .normal)
button.frame = CGRect(x: 50, y: 800, width: 350, height: 50)
button.layer.cornerRadius = 15
button.addTarget(self, action: #selector(didTapAddButton), for: .touchUpInside)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = data[indexPath.row].item
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
#objc private func didTapAddButton() {
let rootVC = addCardViewController()
let navVC = UINavigationController(rootViewController: rootVC)
navVC.modalPresentationStyle = .fullScreen
present(navVC, animated: true)
}
}
class AddCardItem: Object {
#objc dynamic var item: String = ""
#objc dynamic var date: Date = Date()
}
Please change the code on the register CELL Tableview.
yourTableView.register(
UINib.init(nibName: "ProductCVC", bundle: nil),
forCellWithReuseIdentifier: "ProductCVC")
I have been looking all throughout SO on how to interact with a UIButton within a customized tableview cell. All of the answers I have seen are using IBOutlets, however I have not seen a way to do this fully programmatically. I am use to interacting with buttons via button.addTarget. Here are my two ViewControllers, one being the customized tableviewcell and the other being the ViewController.
Here is my customized. I tried using a protocol delegate route, however this has failed.
import UIKit
#objc protocol TableViewNew {
func onClickCell()
}
class NewMoveTableViewCell: UITableViewCell {
var cellDelegate: TableViewNew?
static let identifier = "NewTableViewCell"
private let myImageView: UIImageView = {
let imageView = UIImageView()
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFill
imageView.layer.masksToBounds = true
imageView.backgroundColor = .purple
imageView.layer.cornerRadius = 80/2
return imageView
}()
private let myLabel : UILabel = {
let label = UILabel()
label.text = "test"
label.backgroundColor = .blue
label.textColor = .systemPink
label.adjustsFontSizeToFitWidth = true
label.textAlignment = .center
return label
}()
private let button: UIButton = {
let button = UIButton()
button.setTitle("Invite", for: .normal)
button.backgroundColor = .systemPink
button.layer.cornerRadius = 10
return button
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(myImageView)
addSubview(myLabel)
addSubview(button)
setImageConstratins()
setTitleLabelConstraints()
setButton()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setImageConstratins() {
myImageView.translatesAutoresizingMaskIntoConstraints = false
myImageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
myImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12).isActive = true
myImageView.heightAnchor.constraint(equalToConstant: 80).isActive = true
myImageView.widthAnchor.constraint(equalToConstant: 80).isActive = true
}
func setTitleLabelConstraints() {
myLabel.translatesAutoresizingMaskIntoConstraints = false
myLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
myLabel.leadingAnchor.constraint(equalTo: myImageView.trailingAnchor, constant: 5).isActive = true
myLabel.heightAnchor.constraint(equalToConstant: 80).isActive = true
//myLabel.trailingAnchor.constraint(equalTo: button.leadingAnchor, constant: -12).isActive = true
}
func setButton() {
button.translatesAutoresizingMaskIntoConstraints = false
button.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
button.leadingAnchor.constraint(equalTo: myLabel.trailingAnchor, constant: -5).isActive = true
button.heightAnchor.constraint(equalToConstant: 80).isActive = true
button.widthAnchor.constraint(equalToConstant: 150).isActive = true
button.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12).isActive = true
}
public func configure(with name: String, label: String) {
myLabel.text = label
myImageView.image = UIImage(named: name)
}
override func prepareForReuse() {
super.prepareForReuse()
myLabel.text = nil
myImageView.image = nil
}
#objc func didTapButton(_ sender: Any) {
cellDelegate?.onClickCell()
}
}
Secondly, here is the ViewController that the TableView is within.
import UIKit
class NewMoveViewController: UIViewController {
private let tableView: UITableView = {
let tableView = UITableView()
tableView.rowHeight = 100
return tableView
}()
private var collectionView: UICollectionView?
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: 50, height: 50)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView?.register(NewMoveCollectionViewCell.self, forCellWithReuseIdentifier: NewMoveCollectionViewCell.identifier)
collectionView?.showsHorizontalScrollIndicator = false
title = "Add to Group"
tableView.register(NewMoveTableViewCell.self, forCellReuseIdentifier: NewMoveTableViewCell.identifier)
tableView.delegate = self
tableView.dataSource = self
collectionView?.backgroundColor = .systemBlue
collectionView?.dataSource = self
collectionView?.delegate = self
guard let myCollection = collectionView else {
return
}
view.addSubview(myCollection)
// Do any additional setup after loading the view.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView?.frame = CGRect(x: 0, y: 100, width: view.frame.size.width, height: 50)
tableView.frame = CGRect(x: 0, y: 200, width: view.frame.size.width, height: view.frame.size.height)
}
}
extension NewMoveViewController : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: NewMoveTableViewCell.identifier, for: indexPath) as! NewMoveTableViewCell
cell.cellDelegate = self
cell.configure(with: "", label: "test")
return cell
}
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return false
}
}
extension NewMoveViewController : UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NewMoveCollectionViewCell.identifier, for: indexPath) as! NewMoveCollectionViewCell
return cell
}
}
extension NewMoveViewController : TableViewNew {
func onClickCell() {
print("Pressed")
}
I conformed this ViewController to the protocol from the customized cell and put the function within the cell's cellForRowAt function. When I use this route, I run my app and everything comes up fine, however when I try to click on the customized tableviewcell within the viewcontroller, nothing happens. Any help would be greatly appreciated.
you need to add the action handler to your button:
button.addTarget(self, action: #selector(didTapButton(sender:)), for: .touchUpInside)
I first programmatically created a tableview :
private func setupTableView() {
tableView = UITableView(frame: CGRect(x: 0, y: 180, width: view.frame.width, height: view.frame.height), style: UITableView.Style.plain)
tableView.dataSource = self
tableView.delegate = self
tableView.register(ItemTableViewCell.self, forCellReuseIdentifier: "Cell")
view.addSubview(tableView)
}
and set the cellForRow method as below :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ItemTableViewCell
guard let finalItems = presenter.finalItems?[indexPath.row] else { return cell }
presenter.configure(cell: cell, FinalItem: finalItems)
return cell
}
Then I configure the ItemTableViewCell as below :
class ItemTableViewCell: UITableViewCell {
private var iconImageView : UIImageView = {
let imgView = UIImageView(image: #imageLiteral(resourceName: "Image"))
imgView.contentMode = .scaleAspectFit
imgView.clipsToBounds = true
return imgView
}()
private var titleLabel : UILabel = {
let lbl = UILabel()
lbl.textColor = .black
lbl.font = UIFont.boldSystemFont(ofSize: 12)
lbl.textAlignment = .left
return lbl
}()
func configure(finalItem: FinalItem) {
titleLabel.text = finalItem.title
iconImageView.downloaded(from: finalItem.images_url.small)
}
}
When I push to the DetailViewController with the uinavigationbar, the elements contained in the rows (titles, labels...) are still visible a few milli seconds:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let finalItem = finalItems[indexPath.row]
let detailViewController = ModuleBuilder.createDetailModuleWith(finalItem)
detailViewController.finalItem = finalItem
navigationController?.pushViewController(detailViewController, animated: true)
}
This is not what I am expecting. I never figure this problem out before.
Objective
When the user clicks on any of the 3 blue buttons, all buttons change to the same color.
Note: this is an abstraction of a shared progress view problem, it's therefore important that only one UIView is shared (or mimicked) across my three rows
Here is a compilable Swift project:
import UIKit
class ToggleButton: UIButton {
var connectedView: UIView?
func onPress() {
self.isHidden = true
self.connectedView?.isHidden = false
}
}
class ViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView = UITableView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
var myView: UIView? = nil
var toggleBtn: ToggleButton? = nil
override func viewDidLoad() {
self.setupTableView()
}
fileprivate func setupTableView() {
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.backgroundColor = UIColor.white
self.tableView.isOpaque = true
self.view.addSubview(self.tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "CellIdentifier")
let frame = CGRect(x: 10, y: 10, width: 30, height: 30)
if let view = self.myView, let btn = self.toggleBtn {
cell.addSubview(view)
cell.addSubview(btn)
} else {
let myView = UIView(frame: frame)
myView.backgroundColor = UIColor.green
myView.isHidden = true
cell.addSubview(myView)
let toggleBtn = ToggleButton(frame: frame)
toggleBtn.backgroundColor = UIColor.blue
toggleBtn.addTarget(self, action: #selector(onPress), for: .touchUpInside)
toggleBtn.connectedView = myView
cell.addSubview(toggleBtn)
}
return cell
}
#objc func onPress(_ sender: Any) {
if let button = sender as? ToggleButton {
button.onPress()
}
}
}
Any help appreciated.
The concept of UITableViewCell is made to be very independent each other.
So the only thing you can do it having a bool flag in your ViewController, then you init your 3 cells with this flags.
And finally each time the button is pressed you toggle the flag en reload your tableView.
I am using UICollectionView didSelectItemAt to update a UI label that I set up in my HomeController. So basically when I press the cell I want my text to be updated. However the text doesn't update, I have debugged though and the value changes. I have tried everything, both setNeedsDisplay() and running through main thread (which it already does)
I have quite a lot of code in these classes (I don't use storyboard) but this is the label setup (sits in HomeController):
import UIKit
import CoreData
class mainHomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
static let sharedInstance = HomeController()
override func viewDidLoad() {
super.viewDidLoad()
setupBasketBar()
}
let totNumber: UILabel = {
let label = UILabel()
label.text = "0"
label.numberOfLines = 2
return label
}()
func setupBasketBar() {
self.view.addSubview(totNumber)
totNumber.translatesAutoresizingMaskIntoConstraints = false
totNumber.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: 330).isActive = true
totNumber.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
totNumber.bottomAnchor.constraint(equalTo: view.bottomAnchor,constant: 0).isActive = true
totNumber.heightAnchor.constraint(equalTo: view.heightAnchor,multiplier: 5).isActive = true
}
}
and this sits in the feed cell:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
HomeController.sharedInstance.totNumber.text = ("234")
HomeController.sharedInstance.totNumber.setNeedsDisplay()
}
I have edited out the relevant parts.
This is the whole code for the HomeController:
import UIKit
import CoreData
class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
static let sharedInstance = HomeController()
let cellId = "cellId"
let trendingCellId = "trendingCellId"
let subscriptionCellId = "subscriptionCellId"
let titles = ["Home", "Trending", "Subscriptions", "Account"]
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.isTranslucent = false
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: view.frame.height))
titleLabel.text = "Home"
titleLabel.textColor = UIColor.black
titleLabel.font = UIFont.systemFont(ofSize: 20)
navigationItem.titleView = titleLabel
setupCollectionView()
setupMenuBar()
setupBasketBar()
}
func setupCollectionView() {
if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 0
}
collectionView?.backgroundColor = UIColor.white
collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.register(TrendingCell.self, forCellWithReuseIdentifier: trendingCellId)
collectionView?.register(SubscriptionCell.self, forCellWithReuseIdentifier: subscriptionCellId)
collectionView?.contentInset = UIEdgeInsetsMake(50, 0, 0, 0)
collectionView?.scrollIndicatorInsets = UIEdgeInsetsMake(50, 0, 0, 0)
collectionView?.isPagingEnabled = true
}
lazy var settingsLauncher: SettingsLauncher = {
let launcher = SettingsLauncher()
launcher.homeController = self
return launcher
}()
func handleMore() {
//show menu
settingsLauncher.showSettings()
}
func showControllerForSetting(_ setting: Setting) {
let dummySettingsViewController = UIViewController()
dummySettingsViewController.view.backgroundColor = UIColor.white
dummySettingsViewController.navigationItem.title = setting.name.rawValue
navigationController?.navigationBar.tintColor = UIColor.white
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
navigationController?.pushViewController(dummySettingsViewController, animated: true)
}
func handleSearch() {
scrollToMenuIndex(2)
}
func scrollToMenuIndex(_ menuIndex: Int) {
let indexPath = IndexPath(item: menuIndex, section: 0)
collectionView?.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition(), animated: true)
setTitleForIndex(menuIndex)
}
fileprivate func setTitleForIndex(_ index: Int) {
if let titleLabel = navigationItem.titleView as? UILabel {
titleLabel.text = " \(titles[index])"
}
}
lazy var menuBar: MenuBar = {
let mb = MenuBar()
mb.homeController = self
return mb
}()
func buttonAction(sender: UIButton!) {
let btnsendtag: UIButton = sender
if btnsendtag.tag == 1 {
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc: UINavigationController = storyboard.instantiateViewController(withIdentifier: "NewViewController") as! UINavigationController
self.present(vc, animated: true, completion: nil)
}
}
let totLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
let btn: UIButton = UIButton(frame: CGRect(x: 0, y: 600, width: 500, height: 80))
func setupBasketBar() {
//Checkout button
btn.backgroundColor = UIColor.rgb(36, green: 51, blue: 70)
btn.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
btn.tag = 1
self.view.addSubview(btn)
btn.setTitleColor(UIColor.yellow, for: .normal)
//Button that updates the current amount
totLabel.text = "Total amount"
totLabel.textColor = UIColor.white
self.view.addSubview(totLabel)
//constraints
totLabel.translatesAutoresizingMaskIntoConstraints = false
totLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
totLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
totLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor,constant: 0).isActive = true
totLabel.heightAnchor.constraint(equalTo: view.heightAnchor,multiplier: 0.1).isActive = true
//oldconstraints
/* self.view.addSubview(totNumber)
totNumber.translatesAutoresizingMaskIntoConstraints = false
totNumber.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: 330).isActive = true
totNumber.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
totNumber.bottomAnchor.constraint(equalTo: view.bottomAnchor,constant: 0).isActive = true
totNumber.heightAnchor.constraint(equalTo: view.heightAnchor,multiplier: 0.1).isActive = true*/
}
fileprivate func setupMenuBar() {
navigationController?.hidesBarsOnSwipe = false
let redView = UIView()
redView.backgroundColor = UIColor.rgb(36, green: 51, blue: 70)
view.addSubview(redView)
view.addConstraintsWithFormat("H:|[v0]|", views: redView)
view.addConstraintsWithFormat("V:[v0(50)]", views: redView)
view.addSubview(menuBar)
view.addConstraintsWithFormat("H:|[v0]|", views: menuBar)
view.addConstraintsWithFormat("V:[v0(50)]", views: menuBar)
menuBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
}
override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let index = targetContentOffset.pointee.x / view.frame.width
let indexPath = IndexPath(item: Int(index), section: 0)
menuBar.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally)
setTitleForIndex(Int(index))
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let identifier: String
if indexPath.item == 1 {
identifier = trendingCellId
} else if indexPath.item == 2 {
identifier = subscriptionCellId
} else {
identifier = cellId
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: view.frame.height - 50)
}
}
Okay! looking at the updated code snippet the sharedInstance singleton is definitely not needed - I'd remove that completely.
The didSelectItemAt method then just needs to be this:
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
totNumber.text = "234"
}
I'm guessing your sharedInstance variable is a new instance of the view controller, this is separate from the one that is allocated and displayed from storyboards or segues. You should set sharedInstance equal to self inside viewDidLoad