I have a table view controller that displays names of shopping lists. These shopping lists are created through a shopping list class, which lets me specify the name of the shopping list and items in it. This table view displays around 5 shopping lists (names). When I press one, I go to another table view controller, which shows the items of the shopping list. However, when I go back to the shopping list (names) table view controller and press another shopping list, it still displays the items from the old shopping list and not the one that was pressed. I think I have narrowed the problem down to the cellForItemAt of the second table view controller not being called again.
import UIKit
class List: NSObject {
var name: String
var items: [String?]
var shared: String?
init(name: String, items: [String], shared: String?) {
self.name = name
self.items = items
self.shared = shared
}
}
enum ListType {
case apply
case view
}
class ListViewController: UITableViewController {
//Initialize Variables Here
let cellId = "cellId"
var lists: [List] = [
List(name: "Veggies", items: ["Fruit Loops", "Pasta"], shared: nil),
List(name: "11/17/18", items: ["Eggs", "Green Beans", "Pirate Booty", "Bread", "Milk"], shared: nil),
List(name: "Fruits", items: ["Fruit Loops", "Oranges"], shared: nil),
List(name: "Red Foods", items: ["Apples", "Tomatoes", "Watermelon", "Cherries"], shared: nil),
List(name: "Grains", items: ["Bread Crumbs", "Pasta", "Rice", "Chicken Flavored Rice"], shared: nil)
]
//Create Class Lazy Vars
lazy var newListVC: NewListViewController = {
let launcher = NewListViewController()
// launcher.homeController = self
return launcher
}()
lazy var listItemsVC: ListItemsViewController = {
let launcher = ListItemsViewController()
// launcher.homeController = self
return launcher
}()
//Setup Enums and Switches
var listType: ListType!
override func viewDidLoad() {
super.viewDidLoad()
//Things that both cases have in common:
navigationController?.navigationBar.prefersLargeTitles = true
let addBarButtonItem = UIBarButtonItem(title: "+", style: .plain, target: self, action: #selector(newList)) //+ Button
addBarButtonItem.setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Light", size: 27)!], for: .normal)
addBarButtonItem.setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Light", size: 27)!], for: .selected)
//SWITCH STATEMENT
switch listType as ListType {
case ListType.apply:
//Apply Begin
navigationItem.title = "Apply List"
//Setup Navigation Bar Items
let locateBarButtonItem = UIBarButtonItem(title: "Locate Item", style: .plain, target: self, action: nil)
//Add items to navigation bar
navigationItem.rightBarButtonItems = [addBarButtonItem, locateBarButtonItem]
//Apply End
case ListType.view:
//View Begin
//Setup Navigation Bar
navigationItem.title = "My Lists"
//Add items to navigation bar
navigationItem.rightBarButtonItem = addBarButtonItem
navigationItem.leftBarButtonItem = editButtonItem
//View End
}
//SWITCH STATEMENT END
//Register TableView with Id: cellId
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
#objc func newList() {
newListVC.pageControlFunc(pageView: PageView.name)
navigationController?.pushViewController(newListVC, animated: true) //Then pushes listVC
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lists.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
cell.textLabel?.text = self.lists[indexPath.row].name //Then sets cell of indexPath text = lists value of index path
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
listItemsVC.listName = lists[indexPath.row].name
listItemsVC.listItems = lists[indexPath.row].items
print(listItemsVC.listItems)
navigationController?.pushViewController(listItemsVC, animated: true)
}
}
///////////////////////////////////////////////////////////////////////////
SECOND UITABLEVIEW - NOT UPDATING
///////////////////////////////////////////////////////////////////////////
import UIKit
class ListItemsViewController: UITableViewController {
//Initialize Variables Here
let cellId = "cellId1"
var listName: String?
var listItems: [String?] = []
override func viewDidLoad() {
super.viewDidLoad()
//Things that both cases have in common:
navigationController?.navigationBar.prefersLargeTitles = true
//Set Title
navigationItem.title = listName
//Register TableView with Id: cellId
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
//Delegate method not called on push to view
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
cell.textLabel?.text = listItems[indexPath.row] //Then sets cell of indexPath text = lists value of index path
return cell
}
}
Thanks in advance!
ViewDidLoadis called once, when the ViewController is first loaded into memory. Since your ListsItemsViewController is a strong property on your ListViewController, and you are navigating to it multiple times, nothing is ever telling it to update its views or reload your tableview because it does not get deallocated(so ViewDidLoad and the TableView delegate/datasource methods do not get called). You also haven't added any custom code telling it to update.
If you want to keep those view controllers as class properties of ListViewController, then you can add tableView.reloadData in the ViewWillAppear method of ListsItemsViewController as shown below.
import UIKit
class List: NSObject {
var name: String
var items: [String?]
var shared: String?
init(name: String, items: [String], shared: String?) {
self.name = name
self.items = items
self.shared = shared
}
}
enum ListType {
case apply
case view
}
class ListViewController: UITableViewController {
//Initialize Variables Here
let cellId = "cellId"
var lists: [List] = [
List(name: "Veggies", items: ["Fruit Loops", "Pasta"], shared: nil),
List(name: "11/17/18", items: ["Eggs", "Green Beans", "Pirate Booty", "Bread", "Milk"], shared: nil),
List(name: "Fruits", items: ["Fruit Loops", "Oranges"], shared: nil),
List(name: "Red Foods", items: ["Apples", "Tomatoes", "Watermelon", "Cherries"], shared: nil),
List(name: "Grains", items: ["Bread Crumbs", "Pasta", "Rice", "Chicken Flavored Rice"], shared: nil)
]
//Create Class Lazy Vars
lazy var newListVC: NewListViewController = {
let launcher = NewListViewController()
// launcher.homeController = self
return launcher
}()
lazy var listItemsVC: ListItemsViewController = {
let launcher = ListItemsViewController()
// launcher.homeController = self
return launcher
}()
//Setup Enums and Switches
var listType: ListType!
override func viewDidLoad() {
super.viewDidLoad()
//Things that both cases have in common:
navigationController?.navigationBar.prefersLargeTitles = true
let addBarButtonItem = UIBarButtonItem(title: "+", style: .plain, target: self, action: #selector(newList)) //+ Button
addBarButtonItem.setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Light", size: 27)!], for: .normal)
addBarButtonItem.setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Light", size: 27)!], for: .selected)
//SWITCH STATEMENT
switch listType as ListType {
case ListType.apply:
//Apply Begin
navigationItem.title = "Apply List"
//Setup Navigation Bar Items
let locateBarButtonItem = UIBarButtonItem(title: "Locate Item", style: .plain, target: self, action: nil)
//Add items to navigation bar
navigationItem.rightBarButtonItems = [addBarButtonItem, locateBarButtonItem]
//Apply End
case ListType.view:
//View Begin
//Setup Navigation Bar
navigationItem.title = "My Lists"
//Add items to navigation bar
navigationItem.rightBarButtonItem = addBarButtonItem
navigationItem.leftBarButtonItem = editButtonItem
//View End
}
//SWITCH STATEMENT END
//Register TableView with Id: cellId
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
#objc func newList() {
newListVC.pageControlFunc(pageView: PageView.name)
navigationController?.pushViewController(newListVC, animated: true) //Then pushes listVC
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lists.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
cell.textLabel?.text = self.lists[indexPath.row].name //Then sets cell of indexPath text = lists value of index path
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
listItemsVC.listName = lists[indexPath.row].name
listItemsVC.listItems = lists[indexPath.row].items
print(listItemsVC.listItems)
navigationController?.pushViewController(listItemsVC, animated: true)
}
}
///////////////////////////////////////////////////////////////////////////
SECOND UITABLEVIEW - NOT UPDATING
///////////////////////////////////////////////////////////////////////////
import UIKit
class ListItemsViewController: UITableViewController {
//Initialize Variables Here
let cellId = "cellId1"
var listName: String?
var listItems: [String?] = []
override func viewDidLoad() {
super.viewDidLoad()
//Things that both cases have in common:
navigationController?.navigationBar.prefersLargeTitles = true
//Set Title
navigationItem.title = listName
//Register TableView with Id: cellId
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
//Delegate method not called on push to view
}
//This will always get called when this view controller's view is added to the window
//so you can guarantee it will call your delegate methods to reload the tableView with your new data
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated: animated)
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
cell.textLabel?.text = listItems[indexPath.row] //Then sets cell of indexPath text = lists value of index path
return cell
}
}
The other option would be removing those lazy vars and just initializing those view controllers as needed, so that they get deallocated once you remove them from the stack. This would mean that your tableviews would always reload without having to add any code in ViewWillAppear
import UIKit
class List: NSObject {
var name: String
var items: [String?]
var shared: String?
init(name: String, items: [String], shared: String?) {
self.name = name
self.items = items
self.shared = shared
}
}
enum ListType {
case apply
case view
}
class ListViewController: UITableViewController {
//Initialize Variables Here
let cellId = "cellId"
var lists: [List] = [
List(name: "Veggies", items: ["Fruit Loops", "Pasta"], shared: nil),
List(name: "11/17/18", items: ["Eggs", "Green Beans", "Pirate Booty", "Bread", "Milk"], shared: nil),
List(name: "Fruits", items: ["Fruit Loops", "Oranges"], shared: nil),
List(name: "Red Foods", items: ["Apples", "Tomatoes", "Watermelon", "Cherries"], shared: nil),
List(name: "Grains", items: ["Bread Crumbs", "Pasta", "Rice", "Chicken Flavored Rice"], shared: nil)
]
//Setup Enums and Switches
var listType: ListType!
override func viewDidLoad() {
super.viewDidLoad()
//Things that both cases have in common:
navigationController?.navigationBar.prefersLargeTitles = true
let addBarButtonItem = UIBarButtonItem(title: "+", style: .plain, target: self, action: #selector(newList)) //+ Button
addBarButtonItem.setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Light", size: 27)!], for: .normal)
addBarButtonItem.setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Light", size: 27)!], for: .selected)
//SWITCH STATEMENT
switch listType as ListType {
case ListType.apply:
//Apply Begin
navigationItem.title = "Apply List"
//Setup Navigation Bar Items
let locateBarButtonItem = UIBarButtonItem(title: "Locate Item", style: .plain, target: self, action: nil)
//Add items to navigation bar
navigationItem.rightBarButtonItems = [addBarButtonItem, locateBarButtonItem]
//Apply End
case ListType.view:
//View Begin
//Setup Navigation Bar
navigationItem.title = "My Lists"
//Add items to navigation bar
navigationItem.rightBarButtonItem = addBarButtonItem
navigationItem.leftBarButtonItem = editButtonItem
//View End
}
//SWITCH STATEMENT END
//Register TableView with Id: cellId
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
#objc func newList() {
let newListVC = NewListViewController()
newListVC.pageControlFunc(pageView: PageView.name)
navigationController?.pushViewController(newListVC, animated: true) //Then pushes listVC
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lists.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
cell.textLabel?.text = self.lists[indexPath.row].name //Then sets cell of indexPath text = lists value of index path
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let listItemsVC = ListItemsViewController()
listItemsVC.listName = lists[indexPath.row].name
listItemsVC.listItems = lists[indexPath.row].items
print(listItemsVC.listItems)
navigationController?.pushViewController(listItemsVC, animated: true)
}
}
///////////////////////////////////////////////////////////////////////////
SECOND UITABLEVIEW - NOT UPDATING
///////////////////////////////////////////////////////////////////////////
import UIKit
class ListItemsViewController: UITableViewController {
//Initialize Variables Here
let cellId = "cellId1"
var listName: String?
var listItems: [String?] = []
override func viewDidLoad() {
super.viewDidLoad()
//Things that both cases have in common:
navigationController?.navigationBar.prefersLargeTitles = true
//Set Title
navigationItem.title = listName
//Register TableView with Id: cellId
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
//Delegate method not called on push to view
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
cell.textLabel?.text = listItems[indexPath.row] //Then sets cell of indexPath text = lists value of index path
return cell
}
}
Related
I took my lead from this tutorial: https://kylebashour.com/posts/context-menu-guide
I thought I had everything, yet when I click on the row, nothing happens
UPDATE: Thanks a comment I learned that contextMenuConfigurationForRowAt is called on a long press. Is there a way to call this on a click? I wanted to give users several options for contacting the people listed. But buttons in UITableViewCell doesn't seem to work, so a context menu is the best I can think of, but a long press isn't obvious for interacting with this table view.
import UIKit
class PeerSupportVC: UIViewController {
#IBOutlet weak var peerSupportTableView: UITableView!
var supportArray: NSArray = [];
fileprivate var configuration = Configuration.sharedInstance;
override func viewDidLoad() {
super.viewDidLoad()
self.peerSupportTableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
self.peerSupportTableView.delegate = self;
self.peerSupportTableView.dataSource = self;
self.peerSupportTableView.rowHeight = 200.0
getPeerSupport();
}
func getPeerSupport(){
self.supportArray = ["One","Two","Three"]
DispatchQueue.main.async(execute: {
self.peerSupportTableView.reloadData()
});
}
}
extension PeerSupportVC: UITableViewDelegate {
func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
let item = self.supportArray[indexPath.row]
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { suggestedActions in
let phoneAction = UIAction(title: "Phone Call", image: UIImage(systemName: "person.fill")) { (action) in
DispatchQueue.main.async(execute: {
print("Wants to Phone Call");
});
}
let textAction = UIAction(title: "Text Messsage", image: UIImage(systemName: "person.badge.plus")) { (action) in
DispatchQueue.main.async(execute: {
print("Wants to Text Message");
});
}
return UIMenu(title: "Contact Options", children: [phoneAction, textAction])
}
}
}
extension PeerSupportVC: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("Count of Support Array:",self.supportArray.count);
return self.supportArray.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath);
for viewToRemove in cell.subviews {
viewToRemove.removeFromSuperview();
}
let width = self.peerSupportTableView.frame.width;
if let result = self.supportArray[indexPath.row] as? String{
print(result);
let NameLabel = UILabel(frame: CGRect(x: 180, y: 0, width: width-155, height: 30));
NameLabel.textColor = .black;
NameLabel.text = " "+(result);
NameLabel.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight(rawValue: 400));
NameLabel.adjustsFontSizeToFitWidth = true;
cell.addSubview(NameLabel);
}
return cell;
}
}
I dumbed the code down to share, but this lesser version still doesn't work.
What I want to happen is a menu to pop up on the line that was selected and give the user options on how to contact the person they selected. Any help on displaying the menu would be greatly appreciated.
For reference, here's your code, modified to use a reusable cell:
// simple cell class, based on your code
class PeerCell: UITableViewCell {
let nameLabel = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
nameLabel.translatesAutoresizingMaskIntoConstraints = false
nameLabel.font = .systemFont(ofSize: 12, weight: UIFont.Weight(rawValue: 400))
contentView.addSubview(nameLabel)
let g = contentView.layoutMarginsGuide
NSLayoutConstraint.activate([
nameLabel.topAnchor.constraint(equalTo: g.topAnchor),
nameLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 180.0),
nameLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor),
nameLabel.heightAnchor.constraint(equalToConstant: 30.0),
])
}
}
class PeerSupportVC: UIViewController {
#IBOutlet var peerSupportTableView: UITableView!
var supportArray: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
// register our custom cell
self.peerSupportTableView.register(PeerCell.self, forCellReuseIdentifier: "Cell")
self.peerSupportTableView.delegate = self;
self.peerSupportTableView.dataSource = self;
self.peerSupportTableView.rowHeight = 200.0
getPeerSupport();
}
func getPeerSupport(){
self.supportArray = ["One","Two","Three"]
}
}
extension PeerSupportVC: UITableViewDelegate {
func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
let item = self.supportArray[indexPath.row]
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { suggestedActions in
let phoneAction = UIAction(title: "Phone Call", image: UIImage(systemName: "person.fill")) { (action) in
print("Wants to Phone Call");
}
let textAction = UIAction(title: "Text Messsage", image: UIImage(systemName: "person.badge.plus")) { (action) in
print("Wants to Text Message");
}
return UIMenu(title: "Contact Options", children: [phoneAction, textAction])
}
}
}
extension PeerSupportVC: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("Count of Support Array:",self.supportArray.count);
return self.supportArray.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! PeerCell
let result = self.supportArray[indexPath.row]
print(result)
cell.nameLabel.text = result
return cell;
}
}
As I said in my comment, though, your contextMenuConfigurationForRowAt was working as-is -- just need to long-press on the cell to trigger the call.
I'm tired of searching about what I want, so I will ask here and hope you guys help if possible.
I have a tableview contain segments in each cell and I want to save all cells segment using button [outside the tableview] so I can show them in another table later.
Here is my tableview
here is my view Controller:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
let arr = ["item 1",
"item 2",
"item 3"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(CustomCell.self, forCellReuseIdentifier: "cell")
}
#IBAction func saveButtonAction(_ sender: UIButton) {
// I want to save the cells segmented control selectedSegmentIndex???
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
90
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.textView.text = arr[indexPath.row]
return cell
}
}
and here is my Custom Cell and it contain TextView and Segment Controller I tried to save the segments changes in array but I don't know what to do after lol:
import UIKit
class CustomCell: UITableViewCell {
let textView: UITextView = {
let tv = UITextView()
tv.translatesAutoresizingMaskIntoConstraints = false
tv.font = UIFont.systemFont(ofSize: 16)
tv.isEditable = false
return tv
}()
// var rowIndexPath: Int?
var segmentArray: [Int] = []
lazy var itemSegmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["1", "2", "3"])
sc.translatesAutoresizingMaskIntoConstraints = false
sc.tintColor = UIColor.white
sc.selectedSegmentIndex = 0
sc.addTarget(self, action: #selector(handlePointChange), for: .valueChanged)
return sc
}()
let stackView: UIStackView = {
let sv = UIStackView()
sv.translatesAutoresizingMaskIntoConstraints = false
return sv
}()
#objc func handlePointChange() {
let segChange = itemSegmentedControl.titleForSegment(at: itemSegmentedControl.selectedSegmentIndex)!
segmentArray.append(Int(segChange)!)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
stackView.addSubview(textView)
stackView.addSubview(itemSegmentedControl)
addSubview(stackView)
stackView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
stackView.widthAnchor.constraint(equalToConstant: 400).isActive = true
stackView.heightAnchor.constraint(equalToConstant: 85).isActive = true
itemSegmentedControl.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
itemSegmentedControl.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 5).isActive = true
itemSegmentedControl.widthAnchor.constraint(equalTo: textView.widthAnchor).isActive = true
itemSegmentedControl.heightAnchor.constraint(equalToConstant: 40).isActive = true
textView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
textView.topAnchor.constraint(equalTo: stackView.topAnchor).isActive = true
textView.widthAnchor.constraint(equalTo: stackView.widthAnchor).isActive = true
textView.heightAnchor.constraint(equalToConstant: 40).isActive = true
}
}
Regards and thanks.
First: in the ViewController I added the empty array:
// I moved the segment array from the custom cell class to here
var segmentArray: [Int:Int] = [:]
override func viewDidLoad() {
super.viewDidLoad()
// I made this array to store default state to the items segments
segmentArray = [0:0,1:0,2:0]
}
// with this func I can update the segmentArray
func getSegmentNumber(r: Int, s: Int) {
segmentArray[r] = Int(s)
}
#IBAction func saveButtonAction(_ sender: UIButton) {
// Here I can save the new state for the segment to the firebase or anywhere.
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.textView.text = arr[indexPath.row]
// here to store the index path row
cell.rowIndexPath = indexPath.row
// you need to add the link because it won't work
cell.link = self
return cell
}
Second: in the Custom Cell Class:
// I removed the store array
var segmentArray: [Int] = [] // removed
// I made link to the ViewController
var link: ViewController?
// variable to get the index path row
var rowIndexPath: Int?
// here I can update the state of the segment using the link
#objc func handlePointChange() {
let segChange = itemSegmentedControl.selectedSegmentIndex
link?.getSegmentNumber(r: rowIndexPath!, s: segChange)
}
That worked for me, and I hope you got it.
If you need anything you can ask.
Again thanks to Kudos.
Regards to all
I'm trying to make a note taking app, however, I'm kinda stuck on how to get my save button to work. Here's what I've got so far:
My Add "Item" View
class AddViewController: UIViewController {
#IBOutlet var addShortDescription: UITextField!
#IBOutlet var addLongDescription: UITextView!
public var completion: ((String, String) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
addShortDescription.becomeFirstResponder()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .done, target: self, action: #selector(didTapSave))
self.title = "Add New Item"
}
#IBAction func didTapSave(_ sender: Any) {
if let text = addShortDescription.text, !text.isEmpty, !addLongDescription.text.isEmpty {
completion?(text, addLongDescription.text)
}
}
}
My Main View
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var table: UITableView!
var models: [(ShortDescription: String, LongDescription: String)] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
table.delegate = self
table.dataSource = self
self.title = "Inventory"
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = models[indexPath.row].ShortDescription
cell.detailTextLabel?.text = models[indexPath.row].LongDescription
return cell
}
#IBAction func addNewInventory(){
guard let vc = storyboard?.instantiateViewController(identifier: "add") as? AddViewController else {
return
}
vc.title = "Add New Item"
vc.navigationItem.largeTitleDisplayMode = .never
vc.completion = { addShortDescription, addLongDescription in
self.navigationController?.popToRootViewController(animated: true)
self.models.append((ShortDescription: addShortDescription, LongDescription: addLongDescription))
self.table.isHidden = false
self.table.reloadData()
}
navigationController?.pushViewController(vc, animated: true)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let model = models[indexPath.row]
// Show addLongDescription controller
guard let vc = storyboard?.instantiateViewController(identifier: "inventory") as?
EditViewController else {
return
}
vc.navigationItem.largeTitleDisplayMode = .never
vc.title = "Edit Item"
vc.addShortDescription.text = model.ShortDescription
vc.addLongDescription.text = model.LongDescription
navigationController?.pushViewController(vc, animated: true)
}
}
I have another view where I plan on allowing the user to edit the added items, I'll add that if you think it may be causing some problems.
my problem: I want to open some kind of Profil if a user pushes a Button in a Table-View Cell. The Cells Data is downloaded from Parse.
The idea is based on Instagram, if you click on the username-button on Insta the profile from the user who posted the image will open. I want to create the same code, but i can't create the code to get the user. Can you help me?
Heres some code:
import UIKit
import Parse
class HomeController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let reuseIdentifer = "FeedCell"
var delegate: HomeControllerDelegate?
var newCenterController: UIViewController!
let tableView = UITableView()
//Für Parse:
var users = [String: String]()
var comments = [String]()
var usernames = [String]()
var lastnames = [String]()
var imageFiles = [PFFileObject]()
var wischen: UISwipeGestureRecognizer!
var wischen2: UISwipeGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
getData()
configureNavigationBar()
configurateTableView()
wischen = UISwipeGestureRecognizer()
wischen.addTarget(self, action: #selector(handleMenuToggle))
wischen.direction = .right
wischen.numberOfTouchesRequired = 1
view.addGestureRecognizer(wischen)
wischen2 = UISwipeGestureRecognizer()
wischen2.addTarget(self, action: #selector(handleMenuToggle))
wischen2.direction = .left
wischen2.numberOfTouchesRequired = 1
view.addGestureRecognizer(wischen2)
}
#objc func handleMenuToggle() {
delegate?.handleMenuToggle(forMenuOption: nil)
}
#objc func showProfile() {
let vc: AProfileViewController!
vc = AProfileViewController()
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)
}
func configureNavigationBar() {
navigationController?.navigationBar.barTintColor = .darkGray
navigationController?.navigationBar.barStyle = .black
navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont(name: "Noteworthy", size: 22)!, NSAttributedString.Key.foregroundColor: UIColor.white]
//navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
navigationItem.title = "Mobile Job Board"
navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_menu_white_3x").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleMenuToggle))
navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_mail_outline_white_2x").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(showCreateNewArticle))
}
//MARK: Table View
//skiped table view configuration
}
// - MARK: Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifer, for: indexPath) as! FeedCell
imageFiles[indexPath.row].getDataInBackground { (data, error) in
if let imageData = data {
if let imageToDisplay = UIImage(data: imageData) {
cell.postImage.image = imageToDisplay
}
}
}
cell.descriptionLabel.text = comments[indexPath.row]
cell.userButton.setTitle("\(usernames[indexPath.row]) \(lastnames[indexPath.row])", for: UIControl.State.normal)
cell.userButton.addTarget(self, action: #selector(showProfile), for: .touchUpInside)
return cell
}
//skiped
}
Thanks a lot!
Tom
The issue here is that your button works on a selector and it has no idea about the sender or where it was called from.
I would do this by creating a custom table view cell (e.g. FeedCell) which allows you to set a delegate (e.g. FeedCellDelegate). Set your class as the delegate for the cell and pass into the cell it's current indexPath. You can then return the indexPath in the delegate call.
Example: Note that code has been removed for simplicity and this code has not been tested. This is simply to guide you in the right direction.
View Controller
import UIKit
class HomeController: UIViewController {
// stripped additional information for example
func showProfile(_ username: String) {
let vc: AProfileViewController!
vc = AProfileViewController()
vc.username = username
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)
}
}
extension HomeController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifer, for: indexPath) as! FeedCell
cell.delegate = self
cell.descriptionLabel.text = comments[indexPath.row]
cell.userButton.setTitle("\(usernames[indexPath.row]) \(lastnames[indexPath.row])", for: UIControl.State.normal)
cell.setIndex(indexPath)
return cell
}
}
extension HomeController: FeedCellDelegate {
func didPressButton(_ indexPath: IndexPath) {
let userName = usernames[indexPath.row]
showProfile(username)
}
}
Feed Cell
import UIKit
protocol FeedCellDelegate {
didPressButton(_ indexPath: IndexPath)
}
class FeedCell: UICollectionViewCell {
var delegate: FeedCellDelegate?
var indexPath: IndexPath
#IBOutlet weak var userButton: UIButton
setIndex(_ indexPath: IndexPath) {
self.indexPath = indexPath
}
#IBAction userButtonPressed() {
if(delegate != nil) {
delegate?.didPressButton(indexPath)
}
}
}
You can generically and in a type safe way get the parent responder of any responder with:
extension UIResponder {
func firstParent<T: UIResponder>(ofType type: T.Type ) -> T? {
return next as? T ?? next.flatMap { $0.firstParent(ofType: type) }
}
}
So:
Get the parent tableviewCell of your button in the target action function
Ask your tableview for the index path
Use the index path.row to index into your users array:
#objc func showProfile(_ sender: UIButton) {
guard let cell = firstParent(ofType: UITableViewCell.self),
let indexPath = tableView.indexPath(for: cell) else {
return
}
let user = users[indexPath.row]
... do other stuff here ...
}
I am making a simple tableview with a customCell. and a searchBar above. but getting a strange behavior from tableView. customCell is showing but above it defaultCell is showing as well and data is getting populated into the defaultCell though i am setting data on my customCell.
this is the output i am getting
https://i.imgur.com/xsTIsiz.png
if you look at it closely you will see my custom cell UI is showing under the default cell.
My custom cell:
https://i.imgur.com/J4UpRle.png
This is my code from viewcontroller
import UIKit
class SuraSearchController: UIViewController {
let searchController = UISearchController(searchResultsController: nil)
let reciters = [Reciter(name: "Abdul Basit Abdus Samad", downloadUrl: ""),
Reciter(name: "Abdul Rahman Al-Sudais", downloadUrl: ""),
Reciter(name: "Ali Bin Abdur Rahman Al Huthaify", downloadUrl: ""),
Reciter(name: "Mishary Rashid Alafasy", downloadUrl: ""),
Reciter(name: "Cheik Mohamed Jibril", downloadUrl: ""),
Reciter(name: "Mohamed Siddiq El-Minshawi", downloadUrl: ""),
Reciter(name: "Mahmoud Khalil Al-Hussary", downloadUrl: ""),
Reciter(name: "Ibrahim Walk (English Only)", downloadUrl: ""),
Reciter(name: "Abu Bakr Al Shatri", downloadUrl: "")]
var filteredReciters = [Reciter]()
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// definesPresentationContext = true
initNavBar()
initTableView()
// Do any additional setup after loading the view.
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
func initNavBar() {
// show navbar
self.navigationController?.setNavigationBarHidden(false, animated: true)
// set search bar delegates
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
// Customize Search Bar
searchController.searchBar.placeholder = "Search Friends"
let myString = "Cancel"
let myAttribute = [ NSAttributedStringKey.foregroundColor: UIColor.white ]
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = myString
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(myAttribute, for: .normal)
if #available(iOS 11.0, *) {
let scb = searchController.searchBar
scb.tintColor = UIColor.white
scb.barTintColor = UIColor.white
if let textfield = scb.value(forKey: "searchField") as? UITextField {
textfield.textColor = UIColor.blue
if let backgroundview = textfield.subviews.first {
// Background color
backgroundview.backgroundColor = UIColor.white
// Rounded corner
backgroundview.layer.cornerRadius = 10
backgroundview.clipsToBounds = true
}
}
}
// Set search bar on navbar
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
}
func initTableView() {
tableView.dataSource = self
tableView.delegate = self
tableView.register(UINib(nibName: "SuraSearchCell", bundle: nil), forCellReuseIdentifier: "SuraSearchCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func searchBarIsEmpty() -> Bool {
// Returns true if the text is empty or nil
return searchController.searchBar.text?.isEmpty ?? true
}
func filterContentForSearchText(_ searchText: String, scope: String = "All") {
filteredReciters = reciters.filter({( reciter : Reciter) -> Bool in
return reciter.name.lowercased().contains(searchText.lowercased())
})
tableView.reloadData()
}
func isFiltering() -> Bool {
return searchController.isActive && !searchBarIsEmpty()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension SuraSearchController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering() {
return filteredReciters.count
}
return reciters.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "SuraSearchCell", for: indexPath) as? SuraSearchCell {
let candy: Reciter
if isFiltering() {
candy = filteredReciters[indexPath.row]
} else {
candy = reciters[indexPath.row]
}
cell.textLabel!.text = candy.name
return cell
}
return UITableViewCell()
}
}
extension SuraSearchController: UISearchResultsUpdating {
// MARK: - UISearchResultsUpdating Delegate
func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
}
And code of the tableview cell
import UIKit
class SuraSearchCell: UITableViewCell {
#IBOutlet weak var itemTitle: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configureCell(item: Reciter) {
itemTitle.text = item.name
}
}
cell.textLabel is default UITableViewCell property. you just need to set value to your customCell itemTitle label.
Replace cell.textLabel!.text = candy.name with cell. itemTitle!.text = candy.name like below.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "SuraSearchCell", for: indexPath) as? SuraSearchCell {
let candy: Reciter
if isFiltering() {
candy = filteredReciters[indexPath.row]
} else {
candy = reciters[indexPath.row]
}
cell. itemTitle!.text = candy.name
//OR
cell.configureCell(candy) // IF your candy is of Reciter type
return cell
}
return UITableViewCell()
}
There may be a mistake with reuse identifier name. Match the name with the used one in the code.
Let update cellForRowAtIndex as below
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "SuraSearchCell", for: indexPath) as? SuraSearchCell {
let candy: Reciter
if isFiltering() {
candy = filteredReciters[indexPath.row]
} else {
candy = reciters[indexPath.row]
}
cell.configureCell(candy)
return cell
}
return UITableViewCell()
}