Button from UITableViewController sends data to detailViewController - swift - ios

I have a problem that I cannot wrap my head around.. You cannot create a button action in a UITableViewController.. So I tried to just control + drag from the button to the detailtableViewController and pressed push.. But when I use prepareForSegue and I then click on the button it should send the button text to a string in the detailtableViewController, but sometimes it's not the correct name, because there are multiple cells in the tableView and the name is not always the same..
What I need it to do is, when you click the button "Button:
It should go to this detailtableViewController:
With the name that is set as text to the Button.
The variable that should receive the name of the button is called viaSegue and it is a string.
My UITableViewController:
class feedTableViewController: UITableViewController, PostCellDelegate {
#IBOutlet weak var loadingSpinner: UIActivityIndicatorView!
#IBOutlet weak var profilePicture: UIImageView!
var sendName = "No name"
var facebookProfileUrl = ""
var dbRef: FIRDatabaseReference!
var updates = [Sweet]()
var gottenUserId : Bool? = false
var gottenUserIdWorkout : Bool? = false
override func viewDidLoad() {
super.viewDidLoad()
let logoImage = UIImageView(frame: CGRect(x:0, y:0, width: 60, height: 32))
logoImage.contentMode = .ScaleAspectFit
let logo = UIImage(named: "logo.png")
logoImage.image = logo
self.navigationItem.titleView = logoImage
loadingSpinner.startAnimating()
if let user = FIRAuth.auth()?.currentUser {
let userId = user.uid
let storage = FIRStorage.storage()
// Refer to your own Firebase storage
let storageRef = storage.referenceForURL("**********")
let profilePicRef = storageRef.child(userId+"/profile_pic.jpg")
// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
profilePicRef.dataWithMaxSize(1 * 300 * 300) { (data, error) -> Void in
if (error != nil) {
// Uh-oh, an error occurred!
print("Unable to download image")
} else {
// Data for "images/island.jpg" is returned
// ... let islandImage: UIImage! = UIImage(data: data!)
if (data != nil){
self.profilePicture.image = UIImage(data: data!)
self.profilePicture.layer.cornerRadius = self.profilePicture.frame.size.width/2
self.profilePicture.clipsToBounds = true
}
}
}
}
dbRef = FIRDatabase.database().reference().child("feed-items")
startObersvingDB()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 205
}
func startObersvingDB() {
FIRDatabase.database().reference().child("feed-items").queryOrderedByChild("date").observeEventType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in
var newUpdates = [Sweet]()
for update in snapshot.children {
let updateObject = Sweet(snapshot: update as! FIRDataSnapshot)
newUpdates.append(updateObject)
}
self.updates = newUpdates.reverse()
self.tableView.reloadData()
}) { (error: NSError) in
print(error.description)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return updates.count
}
protocol PostCellDelegate: class {
func postCell(postCell: PostCell, didTouchUpInside button: UIButton)
}
func postCell(postCell: PostCell, didTouchUpInside button: UIButton) {
let identifier = "toDetailtableViewController"
let username = postCell.nameButton.titleLabel?.text
performSegue(withIdentifier: identifier, sender: username)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Lots of stuff happening here
My custom cell:
class updateTableViewCell: UITableViewCell {
#IBOutlet weak var updateLabel: UILabel!
#IBOutlet weak var picView: UIImageView!
#IBOutlet weak var likesLabel: UILabel!
#IBOutlet weak var likeButton: UIButton!
#IBOutlet weak var hand: UIImageView!
#IBOutlet weak var dateLabel: UILabel!
#IBOutlet weak var nameButton: UIButton!
weak var delegate: PostCellDelegate?
var pathDB : String!
var dbRef: FIRDatabaseReference!
var gottenUserId : Bool? = false
var sendNameCell = "No name here"
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
}
#IBAction func likeTapped(sender: AnyObject) {
//print(pathDB)
checkClickOnLikeButton()
}
#IBAction func didTouchUpInsideButton(sender: AnyObject) {
delegate?.postCell(self, didTouchUpInside: button)
}
func checkClickOnLikeButton() {
let dataPathen = self.pathDB
// print(dataPathen)
if let user = FIRAuth.auth()?.currentUser {
let userId = user.uid
FIRDatabase.database().reference().child("feed-items").child(dataPathen).child("likesForPost").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
// Get user value
self.gottenUserId = snapshot.value![userId] as? Bool
// print(self.gottenUserId)
if self.gottenUserId == true {
print("Der er trykket high five før")
FIRDatabase.database().reference().child("feed-items").child(dataPathen).child("likesForPost").child(userId).removeValue()
let greyButtonColor = UIColor(red: 85/255, green: 85/255, blue: 85/255, alpha: 1.0)
self.likeButton.setTitleColor(greyButtonColor, forState: UIControlState.Normal)
self.hand.image = UIImage(named: "high.png")
} else {
print("Der er IKKE trykket like før")
let quoteString = [userId: true]
FIRDatabase.database().reference().child("feed-items").child(dataPathen).child("likesForPost").updateChildValues(quoteString)
let blueButtonColor = UIColor(red: 231/255, green: 45/255, blue: 60/255, alpha: 1.0)
self.likeButton.setTitleColor(blueButtonColor, forState: UIControlState.Normal)
self.hand.image = UIImage(named: "highfive.png")
}
// ...
}) { (error) in
print(error.localizedDescription)
}
}
}
}

Assuming you have already created a custom class for the cell containing the Button, you must create an #IBAction for the didTouchUpInside event. You must also create a segue directly from the UITableViewController to the detailtableViewController (so not from a button or a view, from one view controller to the other). You will need to give this segue an identifier since we're going to be performing it manually.
Once you've hooked up the #IBAction in the cell, we need a way of performing the segue from the cell. To do this, we need a reference to the UITableViewController. We could get it using delegates or maybe responders, recently I've been using responders.
Delegate
Create a protocol for your UITableViewController to conform to.
protocol PostCellDelegate: class {
func postCell(_ postCell: PostCell, didTouchUpInside button: UIButton)
}
Create a delegate variable in your custom cell class call it's didTouchUpInside method from button's #IBAction for that event.
weak var delegate: PostCellDelegate?
#IBAction func didTouchUpInsideButton() {
delegate?.postCell(self, didTouchUpInside: button)
}
Now in your UITableViewController, you must conform to the delegate and set the delegate of the cells in the cellForRowAt method.
class tableViewController: UITableViewController, PostCellDelegate {
//...
// MARK: PostCellDelegate
func postCell(_ postCell: PostCell, didTouchUpInside button: UIButton) {
let identifier = "toDetailtableViewController"
let username = postCell.button.titleLabel?.text
performSegue(withIdentifier: identifier, sender: username)
}
//...
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.delegate = self
return cell
}
//...
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
switch (segue.destination, sender) {
case let (controller as detailtableViewController, username as String):
controller.usernameTextField.text = username
break
default:
break
}
}
}

Related

getting the error of NSUnknownKeyException', reason: setValue:forUndefinedKey: this class is not key value coding-compliant for the key description

I am facing the issue of passing the data from HomeViewController to PostDetailViewController,
I have checked the classes connected to the View Controllers are correct, class connected to the XIB file is PostTableViewCell,
and still getting this error of
'NSUnknownKeyException', reason:
'[
setValue:forUndefinedKey:]: this class is not key value
coding-compliant for the key description
upon clicking the tablecell
HOMEVIEWCONTROLLER
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView:UITableView!
var posts = [Post]()
var db: Firestore!
var postKey:String = ""
private var documents: [DocumentSnapshot] = []
//public var posts: [Post] = []
private var listener : ListenerRegistration!
override func viewDidLoad() {
super.viewDidLoad()
db = Firestore.firestore()
self.navigationController?.navigationBar.isTranslucent = false
tableView = UITableView(frame: view.bounds, style: .plain)
let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "postCell")
tableView.backgroundColor = UIColor(white: 0.90,alpha:1.0)
view.addSubview(tableView)
var layoutGuide:UILayoutGuide!
if #available(iOS 11.0, *) {
layoutGuide = view.safeAreaLayoutGuide
} else {
// Fallback on earlier versions
layoutGuide = view.layoutMarginsGuide
}
tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
retrieveAllPosts()
//checkForUpdates()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func handleLogout(_ sender:Any) {
try! Auth.auth().signOut()
self.dismiss(animated: false, completion: nil)
}
func retrieveAllPosts(){
let postsRef = Firestore.firestore().collection("posts").limit(to: 50)
postsRef.getDocuments { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
let data = document.data()
// self.postKey = document.documentID
let username = data["username"] as? String ?? ""
let postTitle = data["postTitle"] as? String ?? ""
let postcategory = data["postcategory"] as? String ?? ""
let postContent = data["postContent"] as? String ?? ""
let newSourse = Post( _documentId: document.documentID, _username: username, _postTitle: postTitle, _postcategory: postcategory, _postContent: postContent)
self.posts.append(newSourse)
print(self.postKey)
}
self.tableView.reloadData()
}
}
}
}
/* postsRef.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
self.posts = querySnapshot!.documents.flatMap({Post(dictionary: $0.data())})
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}*/
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.set(post: posts[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let post = self.posts[indexPath.row]
//print("row selected: \(indexPath.row)")
//Swift.print(post._documentId!)
let postKey = post._documentId
let postName = post._username
print(postKey! + postName!)
performSegue(withIdentifier: "toDetailView", sender: indexPath)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//segue.forward(posts, to: segue.destination)
guard let details = segue.destination as? PostDetailViewController,
let index = tableView.indexPathForSelectedRow?.row
else {
return
}
details.detailView = posts[index]
}
}
POSTTABLEVIEWCELL
class PostTableViewCell: UITableViewCell {
#IBOutlet weak var usernameLabel: UILabel!
#IBOutlet weak var profileImageView: UIImageView!
#IBOutlet weak var subtitleLabel: UILabel!
#IBOutlet weak var postTextLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// profileImageView.layer.cornerRadius = profileImageView.bounds.height / 2
// profileImageView.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func set(post:Post) {
usernameLabel.text = post._username
postTextLabel.text = post._postTitle
subtitleLabel.text = post._postcategory
}
}
POST DETAIL VIEW CONTROLLER
class PostDetailViewController: UIViewController {
#IBOutlet var usernamelabel: UILabel!
#IBOutlet var posttitlelabel: UILabel!
#IBOutlet var postIdlabel: UILabel!
// #IBOutlet var description: UILabel!
#IBOutlet var postcategorylabel: UILabel!
var detailView: Post?
var postId:String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
postIdlabel?.text = detailView?._documentId
posttitlelabel?.text = detailView?._postTitle
}
/*
// 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.destination.
// Pass the selected object to the new view controller.
}
*/
}
This situations usually happens when you have already set IBOutlet in your XIB file and you comment out it's connecting outlets in code.
Here in your case, In your PostDetailViewController
// #IBOutlet var description: UILabel!
You have commented the description Label, but IBOutlet is still connected in your XIB file.
So, Look for your XIB file and checkout for active IBOutlet Connections and remove it for description label, Clean, Build and Run.
Hope it helps.

Why is nothing being sent to my tableview?

I am creating a news feed, but nothing is being sent to it. I am currently just testing the gamertag (username), body text, and timestamp. Here are my classes:
1) NewPost (create a new post that is sent to the table view)
import Foundation
import UIKit
import Firebase
import FirebaseDatabase
class NewPost: UIViewController, UITextViewDelegate {
#IBOutlet var enterGamertag: UITextField!
#IBOutlet var enterMessage: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//ADDTOLIST BUTTON
#IBAction func addToList(_ sender: UIButton) {
// guard let userProfile = UserService.currentProfile else {
return }
let postRef =
Database.database().reference().child("posts").childByAutoId()
let postObject = [
// "Gametag": [
//// "uid": userProfile.id,
//// "gamertag": userProfile.gamerTag
// ],
"gamerTag": enterGamertag.text as Any,
"bodytext": enterMessage.text as Any,
"timestamp": [".sv":"timestamp"]
] as [String:Any]
postRef.setValue(postObject, withCompletionBlock: { error, ref in
if error == nil {
self.dismiss(animated: true, completion: nil)
} else {
// Handle the error
}
})
// UserService.sharedInstance.validateUsername("Ninja")
}
//dismiss keyboard
#IBAction func dismissKeyboard(_ sender: UITextField) {
self.resignFirstResponder()
}
#IBAction func micPressed(_ sender: UIButton) {
if sender.isSelected {
sender.isSelected = false
} else {
sender.isSelected = true
}
}
#IBAction func logOutPressed(_ sender: UIButton) {
try! Auth.auth().signOut()
// performSegue(withIdentifier: "logOut", sender: self)
}
}
2) feedTable (shows the table view)
import UIKit
import Firebase
class FeedTable: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableFeedView: UITableView!
var posts = [Post]()
//VIEWDIDLOAD
override func viewDidLoad() {
super.viewDidLoad()
// Hide the navigation bar on the this view controller
tableFeedView.delegate = self
tableFeedView.dataSource = self
tableFeedView.register(UINib(nibName: "PostTableViewCell", bundle: nil), forCellReuseIdentifier: "customTableCell")
// self.tableFeedView?.backgroundColor = UIColor.black
tableFeedView.tableFooterView = UIView()
configureTableView()
}
func observePosts() {
let postRef = Database.database().reference().child("posts")
postRef.observe(.value, with: { snapshot in
var tempPosts = [Post]()
for child in snapshot.children {
if let childSnapshot = child as? DataSnapshot,
let dict = childSnapshot.value as? [String:Any],
let gamerTag = dict["gamerTag"] as? String,
let bodytext = dict["bodytext"] as? String,
let timestamp = dict["timestamp"] as? Double {
let post = Post(id: childSnapshot.key, gamerTag: gamerTag, bodyText: bodytext, timestamp: timestamp)
tempPosts.append(post)
}
}
self.posts = tempPosts
self.tableFeedView.reloadData()
})
}
#IBAction func refreshTable(_ sender: UIButton) {
tableFeedView.reloadData()
}
//Cell For Row At
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:PostTableViewCell = tableView.dequeueReusableCell(withIdentifier: "customTableCell", for: indexPath) as! PostTableViewCell
cell .set(post: posts[indexPath.row])
return cell
}
//Number Of Rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
//Automatic Row Height
func configureTableView() {
tableFeedView.rowHeight = UITableViewAutomaticDimension
tableFeedView.estimatedRowHeight = 120.0
}
}
3) PostTableViewCell (the cell that contains the text labels)
import UIKit
class PostTableViewCell: UITableViewCell {
#IBOutlet weak var customMessageBody: UILabel!
#IBOutlet weak var customConsole: UILabel!
#IBOutlet weak var ifMicUsed: UIImageView!
#IBOutlet weak var timeAdded: UILabel!
#IBOutlet weak var gameMode: UILabel!
#IBOutlet weak var customGamerTag: 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 set(post:Post){
customGamerTag.text = post.gamerTag
customMessageBody.text = post.bodyText
customMessageBody.text = "\(post.timestamp) minutes ago."
}
}

inaccessible due to 'internal' protection level swift 3

I am getting this error "'removeCircleLabel' is inaccessible due to 'internal' protection level" on this line of code. I was adding CVCalendar Library to my project.I added the pod but i when i am adding the view controller code in my project that time its giving me this error.
#IBOutlet weak var calendarView: CVCalendarView!
#IBAction func removeCircleAndDot(sender: AnyObject) {
if let dayView = selectedDay {
calendarView.contentController.removeCircleLabel(dayView)// **error on this line**
if dayView.date.day < randomNumberOfDotMarkersForDay.count {
randomNumberOfDotMarkersForDay[dayView.date.day] = 0
}
calendarView.contentController.refreshPresentedMonth()
}
}
public typealias ContentViewController = CVCalendarContentViewController
public final class CVCalendarView: UIView {
// MARK: - Public properties
public var manager: Manager!
public var appearance: Appearance!
public var touchController: TouchController!
public var coordinator: Coordinator!
public var animator: Animator!
public var contentController: ContentViewController!
public var calendarMode: CalendarMode!
public var (weekViewSize, dayViewSize): (CGSize?, CGSize?)
}
// MARK: Delete circle views (in effect refreshing the dayView circle)
extension CVCalendarContentViewController {
func removeCircleLabel(_ dayView: CVCalendarDayView) {
for each in dayView.subviews {
if each is UILabel {
continue
} else if each is CVAuxiliaryView {
continue
} else {
each.removeFromSuperview()
}
}
}
}
MY View Controller Code
import UIKit
import CVCalendar
class MainPageViewController: UIViewController, UITableViewDelegate,
UITableViewDataSource {
struct Color {
static let selectedText = UIColor.white
static let text = UIColor.black
static let textDisabled = UIColor.gray
static let selectionBackground = UIColor(red: 0.2, green: 0.2, blue: 1.0, alpha: 1.0)
static let sundayText = UIColor(red: 1.0, green: 0.2, blue: 0.2, alpha: 1.0)
static let sundayTextDisabled = UIColor(red: 1.0, green: 0.6, blue: 0.6, alpha: 1.0)
static let sundaySelectionBackground = sundayText
}
// MARK: - Properties
#IBOutlet weak var calendarView: CVCalendarView!
#IBOutlet weak var menuView: CVCalendarMenuView!
#IBOutlet weak var monthLabel: UILabel!
#IBOutlet weak var daysOutSwitch: UISwitch!
fileprivate var randomNumberOfDotMarkersForDay = [Int]()
var shouldShowDaysOut = true
var animationFinished = true
var selectedDay:DayView!
var currentCalendar: Calendar?
override func awakeFromNib() {
let timeZoneBias = 480 // (UTC+08:00)
currentCalendar = Calendar.init(identifier: .gregorian)
if let timeZone = TimeZone.init(secondsFromGMT: -timeZoneBias * 60) {
currentCalendar?.timeZone = timeZone
}
}
#IBOutlet weak var topCalBtnView = UIView()
#IBOutlet weak var sideBtnView = UIView()
#IBOutlet weak var calendarBigView = UIView()
#IBOutlet weak var filterBtn = UIButton()
#IBOutlet weak var calTable = UITableView()
#IBOutlet weak var calView = UIView()
var calendarContectObj = CVCalendarContentViewController()
convenience init() {
self.init(nibName:nil, bundle:nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
//Calendar Stuff
if let currentCalendar = currentCalendar {
monthLabel.text = CVDate(date: Date(), calendar: currentCalendar).globalDescription
}
randomizeDotMarkers()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
self.setLayout()
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
}
func setLayout(){
ConstantFile.roundViewCorner(customVw: topCalBtnView!)
ConstantFile.roundViewCorner(customVw: sideBtnView!)
ConstantFile.roundViewCorner(customVw: calendarBigView!)
ConstantFile.makeRoundBtnWithCornerRadius(btn: filterBtn!, cornerRadius: 0.02)
ConstantFile.roundTableViewCorner(tableVw: calTable!)
}
//Mark:- IBAction
#IBAction func toggleMenuBtn(_ sender: Any) {
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.centerDrawwerController?.toggle(MMDrawerSide.left, animated: true, completion: nil)
}
//MARK:- UITableView Delegate and Data Source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellId")
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Mark:- Calendar Stuff
#IBAction func removeCircleAndDot(sender: AnyObject) {
if let dayView = selectedDay {
calendarView.contentController.removeCircleLabel(dayView)
if dayView.date.day < randomNumberOfDotMarkersForDay.count {
randomNumberOfDotMarkersForDay[dayView.date.day] = 0
}
calendarView.contentController.refreshPresentedMonth()
}
}
#IBAction func refreshMonth(sender: AnyObject) {
calendarView.contentController.refreshPresentedMonth()
randomizeDotMarkers()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
calendarView.commitCalendarViewUpdate()
menuView.commitMenuViewUpdate()
}
private func randomizeDotMarkers() {
randomNumberOfDotMarkersForDay = [Int]()
for _ in 0...31 {
randomNumberOfDotMarkersForDay.append(Int(arc4random_uniform(3) + 1))
}
}
/*
// 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.
}
*/
}
By default all the methods, variable, constants, etc are internal. With internal protection level those methods, variable, constants, etc are not accessible outside a module.
removeCircleLabel(:_) is an internal method of the calendar module, you need make it public to access it.
Also do read: What is the 'open' keyword in Swift?
This explains when you should use public and open.
In my quick search i found the function removeCircleLabel in CVCalendarContentViewController on GitHub.
// MARK: Delete circle views (in effect refreshing the dayView circle)
extension CVCalendarContentViewController {
func removeCircleLabel(_ dayView: CVCalendarDayView) {
for each in dayView.subviews {
if each is UILabel {
continue
} else if each is CVAuxiliaryView {
continue
} else {
each.removeFromSuperview()
}
}
}
}
it clearly you can access this method from your controller. There is no protection.Please check your calendarView source with latest one.

iOS development Swift Custom Cells

I'm developing an app in Swift and I have problem with Custom Cells. I have one Custom Cell and when you click on Add button it creates another Custom Cell. Cell has 3 textfields, and 2 buttons. Those textfields are name, price, and amount of the ingredient of meal that I am creating. When I use only one Custom Cell or add one more to make it two, the data is stored properly. But when I add 2 Custom Cell (3 Custom Cells in total) I have problem of wrong price, only last two ingredients are calculated in price. When I add 3 Custom Cells (4 Custom Cells in total) it only recreates first cell with populated data like in first cell.
On finish button tap, I get an fatal error: Found nil while unwrapping Optional value.
View Controller
import UIKit
import CoreData
class AddMealViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
#IBOutlet weak var mealNameTF: UITextField!
#IBOutlet weak var addMealsCell: UITableViewCell!
#IBOutlet weak var finishButton: UIButton!
#IBOutlet weak var resetButton: UIButton!
#IBOutlet weak var addButton: UIButton!
#IBOutlet weak var addMealTableView: UITableView!
#IBOutlet weak var productPrice: UILabel!
let currency = "$" // this should be determined from settings
var priceTotal = "0"
override func viewDidLoad() {
super.viewDidLoad()
addMealTableView.delegate = self
addMealTableView.dataSource = self
borderToTextfield(textField: mealNameTF)
mealNameTF.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return true;
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return counter
}
var counter = 1
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return counter
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:
"addMealsCell", for: indexPath) as! AddMealsTableViewCell
borderToTextfield(textField: (cell.amountTF)!)
borderToTextfield(textField: (cell.ingredientNameTF)!)
//borderToTextfield(textField: cell.normativeTF)
borderToTextfield(textField: (cell.priceTF)!)
return cell
}
#IBAction func addButton(_ sender: UIButton) {
counter += 1
addMealTableView.register(AddMealsTableViewCell.self, forCellReuseIdentifier: "addMealsCell")
addMealTableView.reloadData()
}
#IBAction func resetButton(_ sender: UIButton) {
mealNameTF.text = ""
for c in 0..<counter{
let indexPath = IndexPath(row: c, section:0)
let cell = addMealTableView.cellForRow(at: indexPath) as! AddMealsTableViewCell
cell.amountTF.text = ""
cell.ingredientNameTF.text = ""
// cell.normativeTF.text = ""
cell.priceTF.text = ""
}
productPrice.text = "\(currency)0.00"
priceTotal = "0"
counter = 1
}
#IBAction func finishButton(_ sender: UIButton) {
for c in (0..<counter){
if let cell = addMealTableView.cellForRow(at: IndexPath(row: c, section: 0)) as? AddMealsTableViewCell {
cell.amountTF.delegate = self
cell.ingredientNameTF.delegate = self
// cell.normativeTF.delegate = self
cell.priceTF.delegate = self
guard cell.priceTF.text?.isEmpty == false && cell.amountTF.text?.isEmpty == false && mealNameTF.text?.isEmpty == false && cell.ingredientNameTF.text?.isEmpty == false
else {
return
}
if cell.priceTF.text?.isEmpty == false{
// if (true) {
let tfp = Double((cell.priceTF.text!))!*Double((cell.amountTF.text!))!
var ttp = Double(priceTotal)
ttp! += tfp
priceTotal = String(ttp!)
// }
}}
}
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newMeal = NSEntityDescription.insertNewObject(forEntityName: "Meal", into: context)
let mealName = mealNameTF.text
newMeal.setValue(mealName, forKey: "name")
newMeal.setValue(priceTotal, forKey: "price")
do {
try context.save()
print("Spremljeno")
} catch {
print("Neki error")
}
productPrice.text = currency + priceTotal
}
#IBAction func addNewIngredientButton(_ sender: UIButton) {
}
func borderToTextfield(textField: UITextField){
let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.white.cgColor
border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width: textField.frame.size.width, height: textField.frame.size.height)
border.borderWidth = width
textField.layer.addSublayer(border)
textField.layer.masksToBounds = true
textField.tintColor = UIColor.white
textField.textColor = UIColor.white
textField.textAlignment = .center
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return true;
}
}
Cell
class AddMealsTableViewCell: UITableViewCell, UITextFieldDelegate{
#IBOutlet weak var DropMenuButton: DropMenuButton!
#IBOutlet weak var addNewIngredient: UIButton!
#IBOutlet weak var ingredientNameTF: UITextField!
// #IBOutlet weak var normativeTF: UITextField!
#IBOutlet weak var amountTF: UITextField!
#IBOutlet weak var priceTF: UITextField!
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.endEditing(true)
return true;
}
override func prepareForReuse() {
self.amountTF.text = ""
self.priceTF.text = ""
self.ingredientNameTF.text = ""
}
#IBAction func DropMenuButton(_ sender: DropMenuButton) {
DropMenuButton.initMenu(["kg", "litre", "1/pcs"], actions: [({ () -> (Void) in
print("kg")
sender.titleLabel?.text = "kg"
}), ({ () -> (Void) in
print("litre")
sender.titleLabel?.text = "litre"
}), ({ () -> (Void) in
print("1/pcs")
sender.titleLabel?.text = "1/pcs"
})])
}
#IBAction func addNewIngredient(_ sender: UIButton) {
let name = ingredientNameTF.text
let amount = amountTF.text
let price = priceTF.text
// let normative = normativeTF.text
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newIngredient = NSEntityDescription.insertNewObject(forEntityName: "Ingredient", into: context)
newIngredient.setValue(name, forKey: "name")
// newIngredient.setValue(normative, forKey: "normative")
newIngredient.setValue(amount, forKey: "amount")
newIngredient.setValue(price, forKey: "price")
do {
try context.save()
print("Spremljeno")
} catch {
print("Neki error")
}
}
}
Your code is very difficult to read, but I suspect the problem may be here:
func numberOfSections(in tableView: UITableView) -> Int {
return counter
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return counter
}
You're returning the same number of rows for both the sections and rows for sections. So if you have 1 ingredient you are saying there is 1 section with 1 row. But if you have 2 ingredients you are saying there are 2 sections, each with 2 cells (4 cells total).
There are many other things to fix with your code, here are a few:
The biggest thing is that you are making this very difficult with the counter variable you have. If instead you have an array of ingredients
var ingredients = [Ingredient]()
You can use that to setup everything for the count of your table. Something like this:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ingredients.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:
"addMealsCell", for: indexPath) as! AddMealsTableViewCell
let ingredient = ingredients[indexPath.row]
cell.ingredientNameTF.text = ingredient.name
cell.normativeTF.text = ingredient.normative
cell.amountTF.text = ingredient.amount
cell.priceTF.text = ingredient.price
return cell
}
All of these can be set in interface builder (you dont need lines of code in your view did load for them):
addMealTableView.delegate = self
addMealTableView.dataSource = self
mealNameTF.delegate = self
This line should be in your viewDidLoad function, you only need to register the class once, you're doing it everytime add is pressed.
addMealTableView.register(AddMealsTableViewCell.self, forCellReuseIdentifier: "addMealsCell")
Your action names should be actions
#IBAction func addButtonPressed(_ sender: UIButton)
#IBAction func resetButtonPressed(_ sender: UIButton)
#IBAction func finishButtonPressed(_ sender: UIButton)
Thanks. Now when that ViewController loads I have no cells. My array is now empty so I have to implement some code to addButton which creates another cell and reloads tableView. How can I do that?
You just need to add a new ingredient object to the ingredients array and reload the data of the table view.
#IBAction func addButtonPressed(_ sender: UIButton) {
let newIngredient = Ingredient()
ingredients.append(newIngredient)
tableView.reloadData()
}

Swift Adding Button Action to TableView Cell

I'm trying to create a button within my custom tableview cell that has the action of creating a Parse class if it isn't already created and applying the text of the label of the row that the button clicked occurred as the value for the "following" column and set the "follower" column value as the username of the current loggedin user. Currently I have an error at the let usernameLabel in the addUser IBAction that my Class does not have a member named objectAtIndex. What is the best way to achieve what I'm looking for?
I have created the outlets in SearchUsersRegistrationTableViewCell.swift
import UIKit
class SearchUsersRegistrationTableViewCell: UITableViewCell {
#IBOutlet var userImage: UIImageView!
#IBOutlet var usernameLabel: UILabel!
#IBOutlet weak var addUserButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
userImage.layer.borderWidth = 1
userImage.layer.masksToBounds = false
userImage.layer.borderColor = UIColor.whiteColor().CGColor
userImage.layer.cornerRadius = userImage.frame.width/2
userImage.clipsToBounds = true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Here is my table functionality and the action that I tried to apply to my addUserButton:
import UIKit
class SearchUsersRegistrationViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var userArray : NSMutableArray = []
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
loadParseData()
var user = PFUser.currentUser()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadParseData() {
var query : PFQuery = PFUser.query()
query.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]!, error:NSError!) -> Void in
if error == nil {
if let objects = objects {
println("\(objects.count) users are listed")
for object in objects {
self.userArray.addObject(object)
}
self.tableView.reloadData()
}
} else {
println("There is an error")
}
}
}
let textCellIdentifier = "Cell"
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.userArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! SearchUsersRegistrationTableViewCell
let row = indexPath.row
var individualUser = userArray[row] as! PFUser
var username = individualUser.username as String
var profileImage = individualUser["profileImage"] as! PFFile
profileImage.getDataInBackgroundWithBlock({
(result, error) in
cell.userImage.image = UIImage(data: result)
})
cell.usernameLabel.text = username
cell.addUserButton.tag = row
cell.addUserButton.addTarget(self, action: "addUser:", forControlEvents: .TouchUpInside)
return cell
}
#IBAction func addUser(sender: UIButton){
let usernameLabel = self.objectAtIndex(sender.tag) as! String
var following = PFObject(className: "Followers")
following["following"] = usernameLabel.text
following["follower"] = PFUser.currentUser().username //Currently logged in user
following.saveInBackground()
}
#IBAction func finishAddingUsers(sender: AnyObject) {
self.performSegueWithIdentifier("finishAddingUsers", sender: self)
}
}
I'm assuming the usernameLabel is on the same contentView as the UIButton sender. If that's the case you can add a tag to the usernameLabel and do this
let usernameLabel = sender.superview.viewWithTag(/*Put tag of label here*/)
I'm on a mobile so I don't know if viewWithTag is the right name of the method, but it's something similar.
hope this helps.
You are getting the error because you are using self instead of tableView
let usernameLabel = self.objectAtIndex(sender.tag) as! String
let usernameLabel = tableView.objectAtIndex(sender.tag) as! String
However, this will still give you an error because UITableViewCell cannot be cast as a String.
This is a better option:
if let surtvc = tableView.objectAtIndex(sender.tag) as? SearchUsersRegistrationTableViewCell {
// surtvc.usernameLabel...
// the rest of your code goes here
}

Resources