I want to make programmatically segue from TableView. Content of the cells is dynamic - the're changing, so I can't wrap segue to the number of row (ex. indexPath.row = 1). My array is like that:
myArray = [value1, value2, value3]
But value1 can be today "A", but tomorrow will be "B". So today value1 should redirect to AController, but tomorrow - to BController. Name of the value is of course displayed in the TableView.
I suppose prepareForSegue should be based on name of the value (ex. if name of the value is 'A', then...). But I don't know the method.
Any help will be appreciated :)
To be more clear - how my array is generated:
let cal = NSCalendar.currentCalendar()
let fmt = NSDateFormatter()
var countDays = [String]()
override func viewDidLoad() {
super.viewDidLoad()
fmt.dateFormat = "EEEE"
fmt.locale = NSLocale(localeIdentifier: "pl_PL")
var date = cal.startOfDayForDate(NSDate())
while countDays.count < 7 {
let weekDay = cal.component(.Weekday, fromDate: date)
if weekDay != 0 {
countDays.append(fmt.stringFromDate(date))
}
date = cal.dateByAddingUnit(.Day, value: 1, toDate: date, options: NSCalendarOptions(rawValue: 0))!
}
print(countDays)
You can use "didselectRowAtIndex" delegate method of tableview. You will get the current index path of cell which user has selected/clicked.Use this index path to retrieve corresponding object in your array.Next check the value in retrieved object "A" or "B" using if/else, depending on this you can launch your "AController" or "Controller".Use prepare for segue to launch you specific controller.
Note : all this logic should be done in you "didselectRowAtIndex" method.
Hope this helps.
Ok, I solved this with code:
let cell: UITableViewCell =
tableView.cellForRowAtIndexPath(indexPath)!
let str: String = cell.textLabel!.text!
if str.containsString("A") {
performSegueWithIdentifier("AMonday", sender:self)
}
Easy, but finding this was painful ;)
Related
I'm trying to change the cell backgroungColor after 3.5 month. I have a textField where i put the date and after 3.5 month of that date I want to change the color of the cell in red.
I tried this where date1 is the date from textField and date2 is this from (isToday) where i have put 106 day = 3.5 month
let isToday= Date.now.addingTimeInterval(106)
func isSameDay(date1: Date, date2: Date) -> Bool {
let diff = Calendar.current.dateComponents([.day], from: date1, to: date2)
if diff.day == 0 {
return true
}
else {
return false
}
}
Inside cellForRowAt i have used like this
var documentSendDate = "05.08.2022"// this is example to be more understandable
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM/dd/yyyy"
let date = dateFormatter.date(from: documentSendDate)
if date != nil {
let isDayToday = isSameDay(date1: date!, date2: isToday) // here I call the function above
if isDayToday == true {
if customer.isToday == true {
cell.backgroundColor = .red
}
}
}
But I have this checkBox and when I check it or uncheck it change the color of the random cells. Can someone help me with this please?
Here is how i wanted to look.
UITableView is a recycle-list view, so it will reuse the cell UI instance to display data for the corresponding indexPath.
First, modify your code to add a new way of dateFormatter declaration.
// Use lazy var to reduce initialization cost
// Because initializing a new DateFormatter is not cheap, it can consume CPU time like initializing a new NumberFormatter
// lazy var will be only initialized once on the first call/use
lazy var dateFormatter = DateFormatter()
func viewDidLoad() {
super.viewDidLoad()
dateFormatter.dateFormat = "MMM/dd/yyyy"
}
It is a reusable UI, so UI won't hold the data or state. The cellForRowAt will be called multiple times when you scroll tableView or when tableView needs to re-layout,... to display the corresponding data-state for each indexPath.
That is why you must not initialize or do some big calculations/long waiting here. It will freeze/delay your UI (ref: DispatchQueue.main or MainQueue).
So inside your cellForRowAt function, you need to add logic for all cases if you use switch/if-else.
var documentSendDate = "05.08.2022"// this is example to be more understandable
// Here I combine all checks into one if-else
// Order of check is left-to-right.
// It is condition1 AND condition2 AND condition3 (swift syntax)
if let date = dateFormatter.date(from: documentSendDate),
let isDayToday = isSameDay(date1: date!, date2: isToday),
customer.isToday == true {
cell.backgroundColor = .red
} else {
cell.backgroundColor = .clear // or your desired color
}
Aim :
To be able to display the days selected and the time picked by the user in the same row of the table view. The time should appear at the top and the days selected should appear at the bottom, both in the same row, just like an alarm clock.
Work :
This is the relationship I've got setup :
and this is how I save the days that are selected from a UITable and the time from a UIDatepicker when the save button is tapped :
#IBAction func saveButnTapped(_ sender: AnyObject)
{
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext //creates an object of a property in AppDelegate.swift so we can access it
let bob = Bob(context: context)
//save the time from UIDatePicker to core data
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
bob.timeToPing = dateFormatter.string(from: timePicked.date)
// save the days selected to core data
for weekday in filteredWeekdays
{
var day = Days(context: context) //create new Days object
day.daysSelected = weekday as NSObject? //append selected weekday
bob.addToTimeAndDaysLink(day) //for every loop add day object to bob object
}
//Save the data to core data
(UIApplication.shared.delegate as! AppDelegate).saveContext()
//after saving data, show the first view controller
navigationController!.popViewController(animated: true)
}
Now that the data is once saved, I get the data :
func getData()
{
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do
{
bobs = try context.fetch(Bob.fetchRequest())
}
catch
{
print("Fetching failed")
}
}
Attempt to get the days selected :
I tried to follow this, the below comments and a formerly deleted answer to this question to do this :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = UITableViewCell()
let bob = bobs[indexPath.row]
cell.textLabel?.text = bob.timeToPing?.description
// retrieve the days that are selected
var daysArray: [Days] = []
daysArray = bob.timeAndDaysLink?.allObjects as! [Days]
for days in daysArray
{
print (days.daysSelected?.description)
cell.textLabel?.text = days.daysSelected! as! String
}
return cell
}
EDIT :
print(daysArray) gives this :
[<Days: 0x6080000a5880> (entity: Days; id: 0xd000000000040000 <x-coredata://30B28771-0569-41D3-8BFB-D2E07A261BF4/Days/p1> ; data: <fault>)]
print(daysArray[0]) gives this :
<Days: 0x6080000a5880> (entity: Days; id: 0xd000000000040000 <x-coredata://30B28771-0569-41D3-8BFB-D2E07A261BF4/Days/p1> ; data: <fault>)
How to save days
let weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
var filteredWeekdays: [String] = []
#NSManaged public var daysSelectedbyUser: NSSet
And then
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
selectedWeekdays()
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)
{
selectedWeekdays()
}
func selectedWeekdays()
{
if let selectedRows = tableView.indexPathsForSelectedRows
{
let rows = selectedRows.filter {$0.section == 0}.map{ $0.row}
filteredWeekdays = rows.map{ weekdays[$0] }
print(filteredWeekdays)
}
}
Many thanks!
OK based on your latest comment that the crash occur on this line:
cell.textLabel?.text = days.value(forKey: "daySelected") as! String
It's clearly pointing to the typo you've made in key name. You have: daySelected and should be (based on your core data model) daysSelected, but nevertheless it's not very good approach to use values for your core data entity and also force type like that. To make it better I suggest replacing this line with:
cell.textLabel?.text = days.daysSelected!
This should be already a String since this is a String in CoreData. In case it's optional (should be an optional), you shouldn't force it. I will assume that whenever data will be not there you will just display empty cell, so even better it will be:
cell.textLabel?.text = days.daysSelected ?? ""
This will produce empty string to text, whenever (for some reason) data will be not there.
EDIT
So for additional piece of code you put in your question:
In your CoreData field daysSelected is type of String?, right?
Then you assign timeAndDateLink to NSSet<String>, right? But expected value here should be NSSet<Days>.
So let's edit your input code a bit ( i will put comment on every line):
let bob = Bob(context: context) /* create new Bob object */
for weekday in filteredWeekdays {
var day = Days(context: context) /* create new Days object */
day.daysSelected = weekday /* append selected weekday */
bob.addToTimeAndDaysLink(day) /* for every loop add day object to bob object */
}
I hope everything is clear in above example. You may have a problem with a compiler in that case, because if you choose generate class for entities you will endup with two func with the same name but different parameter (in Swift this should be two different functions, but Xcode sometimes pointing to the wrong one). If you hit that problem try:
let bob = Bob(context: context) /* create new Bob object */
var output: NSMutableSet<Days> = NSMutableSet()
for weekday in filteredWeekdays {
var day = Days(context: context) /* create new Days object */
day.daysSelected = weekday /* append selected weekday */
output.add(day)
}
bob.addToTimeAndDaysLink(output) /* this will assign output set to bob object */
You should also rename your Days entity to Day to avoid future confusion that we have right now, days as array will only be in relation from other entities to this not entity itself.
I don't know why no one uses FetchedResultsController, which is made for fetching NSManagedObjects into tableView, but it doesn't matter I guess...
Problem in this question is that you didn't post here your NSManagedObject class for the variable, so I cannot see which type you set there (Should be Transformable in CoreData model and [String] in NSManagedObject class...)
Ignoring all force unwraps and force casting and that mess (which you should pretty damn well fix as first, then it won't crash at least but just don't display any data...)
Days selected by user is NSSet, which it sure shouldn't be.
Please provide you NSManagedObjectClass in here so I can edit this answer and solve your problem...
My app counts the days between a date and NSDate(). When I released it, a user could only save one date, a title and a background image.
Now I have a UICollectionView with the option to save more than one date, and it will create a cell by appending a date, title and image string to their respective arrays.
The app has been completely changed, so I'm struggling with how to check whether a user has saved a date, and if they have, add that info to the arrays to create a cell.
But, I want this to only been checked once - the first time the app is opened from update or fresh install.
Here is my thinking about it, it doesn't work by the way.
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
if userDefault.objectForKey("day") == nil {
} else {
// Add the first date created from previous version
let day = userDefault.objectForKey("day") as? String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMMM yyyy hh:mm a"
let date = dateFormatter.dateFromString(day!)!
let date1 = dateFormatter.stringFromDate(date)
addDateToArray(date1)
// Add the since text
let text = userDefault.objectForKey("sinceText") as? String
addSinceLabelToArray(text!)
//Add the image background
let image = userDefault.objectForKey("khoury") as! String
addThemeToImagesArray(image)
}
What happens with the code above is it returns nil. I am expecting it to create the first cell, so that the user can see the date they have saved.
You can use another boolean value in NSUserDefaults to detect the first run:
let defaults = NSUserDefaults.standardUserDefaults()
if (!defaults.boolForKey("migrated")) {
defaults.setBool(true, forKey: "migrated")
// ... anything else
}
Create an array within your view controller.
var dates = [NSDate]()
Then in viewDidLoad:
if let retrieved = userDefault.objectForKey("day") {
dates = retrieved as! [NSDate]
}
Then reload your collection view
I was trying to make a table show dates from a calendar in the cells but when I wrote the array it gave me the error of 'Unresolved Identifier for "Date"'
Here is the code:
import UIKit
class DatesTableViewController: UITableViewController {
// MARK: Properties
var dates = [Date]()
override func viewDidLoad() {
super.viewDidLoad()
func loadSampleDates() {
let date1 = Date(print(CALENDAR_CLOCK))!
let date2 = Date(print(CALENDAR_CLOCK))!
let date3 = Date(print(CALENDAR_CLOCK))!
let date4 = Date(print(CALENDAR_CLOCK))!
dates += [date1, date2, date3, date4]
}
The file is in the correct group, it is pointing to an existing table and cell, I am just unsure what else to check for.
I will preface this by saying I am newer to Swift so I might just be simply missing an obvious mistake, but based on the iOS Developer site this seems to be the correct way to write this code.
Date is an unresolved identifier (unless it's a separate class you wrote yourself) — you probably want to use NSDate:
import UIKit
class DatesTableViewController: UITableViewController {
// MARK: Properties
dynamic var dates = [NSDate]()
override func viewDidLoad() {
super.viewDidLoad()
func loadSampleDates() {
let date1 = NSDate(print(CALENDAR_CLOCK))
let date2 = NSDate(print(CALENDAR_CLOCK))
let date3 = NSDate(print(CALENDAR_CLOCK))
let date4 = NSDate(print(CALENDAR_CLOCK))
dates += [date1, date2, date3, date4]
}
}}
Note that the NSDate print function will always return a result — it's not optional, so there's no need to use an ! to force-unwrap it.
Im making a simple planner app which sends notifications to users at specific times that events occur.
I have set up a table to store the data and I am storing individual values inside of an array.
I am encountering a problem outputting the NSDates that I have stored inside of my array.
import UIKit
extension NSDate {
convenience init(dateString:String, format:String="h-mm a") {
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone.defaultTimeZone()
formatter.dateFormat = format
let d = formatter.dateFromString(dateString)
self.init(timeInterval:0, sinceDate:d!)
}
class MedicineTableViewController: UITableViewController {
//MARK Properties
var medicines = [Medicine]()
override func viewDidLoad() {
super.viewDidLoad()
loadSampleMedicine()
}
func loadSampleMedicine() {
let medicine1 = Medicine(name: "Inhaler", time1: NSDate(dateString: "08:00 a"), time2: NSDate(dateString: "10:00 a"), time3: NSDate(dateString: "02:00 p"), time4: NSDate(dateString: "06:00 p"), time5: NSDate(dateString: "10:00 p"))
medicines.append(medicine1!)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return medicines.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "MedicineTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MedicineTableViewCell
let medicine = medicines[indexPath.row]
cell.nameLabel.text = medicine.name
cell.takeAt.text = "Take At:"
cell.time1Label.text = medicine.time1
cell.time2Label.text = medicine.time2
cell.time3Label.text = medicine.time3
cell.time4Label.text = medicine.time4
cell.time5Label.text = medicine.time5
return cell
}
This returns the error "Cannot assign a value of 'NSDate' to a value of type String?"
Is there a way to convert these NSDates into strings?
I have come up with some other possible solution but it involves reworking the whole application so I'd prefer to avoid them if possible.
My possible solution is to rework the data that the user inputs to be a pickerView which has 3 columns one cycling the numbers 01 through to 12, the second 00 to 59 and the third am and pm. and then take the overall string produced and store it in the array. This would allow me to easily print it out since it is just a stored string. Then when I come to the stage at which I am making the notification system I could use the "dateString" function to convert from strings to dates and then program my notifications from that.
So overall I would like to know if I'm able to just print out the NSDates stored in my array or if not if my possible solution would work?
Thanks.
You can use NSDateFormatter. There is a function called stringFromDate. Here is an example.
var date = NSDate() //Or whatever your date is
var stringDate = NSDateFormatter().stringFromDate(date)