How to change Event Dot Color in FSCalender - swift3

Here is my code. I am trying to change the dot color but I did not find any solution. Thanks
func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
return 1;
}
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventColorFor date: Date) -> UIColor? {
return UIColor.red
}
Here is an example image of these event-dots:

This example is taken from here. Basically you just use the given method, check for event-type or something like that and return a color of your favour.
//Used by one of the example methods
var datesWithEvent = ["2015-10-03", "2015-10-06", "2015-10-12", "2015-10-25"]
var datesWithMultipleEvents = ["2015-10-08", "2015-10-16", "2015-10-20", "2015-10-28"]
//Used in one of the example methods
fileprivate lazy var dateFormatter2: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
The complete example is to long for embedding, so i only took 2 example methods. I added the fields from the example, to have an "complete" example of how such a method could look like.
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventColorFor date: Date) -> UIColor? {
//Do some checks and return whatever color you want to.
return UIColor.purple
}
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventDefaultColorsFor date: Date) -> [UIColor]? {
let key = self.dateFormatter2.string(from: date)
if self.datesWithMultipleEvents.contains(key) {
return [UIColor.magenta, appearance.eventDefaultColor, UIColor.black]
}
return nil
}
For better understanding have a look at linked example class in Github. That example is pretty self explanatory.

Related

SwiftUI combine nil data

I have created a class to perform a network request and parse the data using Combine. I'm not entirely certain the code is correct, but it's working as of now (still learning the basics of Swift and basic networking tasks). My Widget has the correct data and is works until the data becomes nil. Unsure how to check if the data from my first publisher in my SwiftUI View is nil, the data seems to be valid even when there's no games showing.
My SwiftUI View
struct SimpleEntry: TimelineEntry {
let date: Date
public var model: CombineData?
let configuration: ConfigurationIntent
}
struct Some_WidgetEntryView : View {
var entry: Provider.Entry
#Environment(\.widgetFamily) var widgetFamily
var body: some View {
VStack (spacing: 0){
if entry.model?.schedule?.dates.first?.games == nil {
Text("No games Scheduled")
} else {
Text("Game is scheduled")
}
}
}
}
Combine
import Foundation
import WidgetKit
import Combine
// MARK: - Combine Attempt
class CombineData {
var schedule: Schedule?
var live: Live?
private var cancellables = Set<AnyCancellable>()
func fetchSchedule(_ teamID: Int, _ completion: #escaping (Live) -> Void) {
let url = URL(string: "https://statsapi.web.nhl.com/api/v1/schedule?teamId=\(teamID)")!
let publisher = URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.decode(type: Schedule.self, decoder: JSONDecoder())
//.catch { _ in Empty<Schedule, Error>() }
//.replaceError(with: Schedule(dates: []))
let publisher2 = publisher
.flatMap {
return self.fetchLiveFeed($0.dates.first?.games.first?.link ?? "")
}
Publishers.Zip(publisher, publisher2)
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: {_ in
}, receiveValue: { schedule, live in
self.schedule = schedule
self.live = live
completion(self.live!)
WidgetCenter.shared.reloadTimelines(ofKind: "NHL_Widget")
}).store(in: &cancellables)
}
func fetchLiveFeed(_ link: String) -> AnyPublisher<Live, Error /*Never if .catch error */> {
let url = URL(string: "https://statsapi.web.nhl.com\(link)")!
return URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.decode(type: Live.self, decoder: JSONDecoder())
//.catch { _ in Empty<Live, Never>() }
.eraseToAnyPublisher()
}
}
Like I said in the comments, it's likely that the decode(type: Live.self, decoder: JSONDecoder()) returns an error because the URL that you're fetching from when link is nil doesn't return anything that can be decoded as Live.self.
So you need to handle that case somehow. For example, you can handle this by making the Live variable an optional, and returning nil when link is empty (or nil).
This is just to set you in the right direction - you'll need to work out the exact code yourself.
let publisher2 = publisher1
.flatMap {
self.fetchLiveFeed($0.dates.first?.games.first?.link ?? "")
.map { $0 as Live? } // convert to an optional
.replaceError(with: nil)
}
Then in the sink, handle the nil:
.sink(receiveCompletion: {_ in }, receiveValue:
{ schedule, live in
if let live = live {
// normal treatment
self.schedule = schedule
self.live = live
//.. etc
} else {
// set a placeholder
}
})
SwiftUI and WidgetKit work differently. I needed to fetch data in getTimeline for my IntentTimelineProvider then add a completion handler for my TimelineEntry. Heavily modified my Combine data model. All credit goes to #EmilioPelaez for pointing me in the right direction, answer here.

SwiftUI display yesterday's date

How do I list yesterday's date in SwiftUI? It probably is a simple answer but I'm just learning to code and for some reason I can't seem to find the solution anywhere. Is it because it is too easy?
struct DateShown: View {
let datechoice: Datechoice
var body: some View {
Text(currentDate(date: Date()))
.font(.headline)
.fontWeight(.bold)
.foregroundColor(.blue)
}
func currentDate(date: Date!) -> String {
let formatter = DateFormatter()
formatter.locale = .current
formatter.dateFormat = "MMMM d, yyyy"
return date == nil ? "" : formatter.string(from: date)
}
}
I would rather use View extensions, though you also need Date formatting so I went the easier way and extended your solution. If the number at line "dayComponent.day" is positive, you go futher in time. I tested under:
swift 5
xcode 11.3.1
iOS 13.3.1 non beta
func yesterDay() -> String {
var dayComponent = DateComponents()
dayComponent.day = -1
let calendar = Calendar.current
let nextDay = calendar.date(byAdding: dayComponent, to: Date())!
let formatter = DateFormatter()
formatter.locale = .current
formatter.dateFormat = "MMMM d, yyyy"
return formatter.string(from: nextDay). //Output is "March 6, 2020
}
Usage is the same as yours:
Text(yesterDay())

How to change Month View to Week View vice versa for JTAppleCalendar

Hi newBiew in JTAppleCalendar.
I follow this link for JTAppleCalendar.
https://www.youtube.com/watch?v=CQNotydm58s&index=6&list=PLpqJf39XekqyUG7dxcqGO0JNprryysv9Q
I have this Problem:
How to I show calendar when user click a button to change monthView to WeekView or from week View to month View
How to I change the calendar size programmatically for CalendarView and mainStack as they have constrains?
I believe I need to handle configureCalendar as below but how to change programmatically month view to week view vice versa.
I have a stack (Call it mainStack) which used to contain CalendarView
Layout for the Calendar view :
#IBOutlet weak var CalendarView : JTAppleCalendarView!<br/>
#IBOutlet weak var mainStack: UIStackView!<br/>
extension MyCalendar: JTAppleCalendarViewDataSource, JTAppleCalendarViewDelegate {
func configureCalendar( _ calendar:JTAppleCalendarView) -> ConfigurationParameters {
formatter.dateFormat = "yyyy MM dd"
formatter.timeZone = Calendar.current.timeZone
formatter.locale = Calendar.current.locale
let startDate = formatter.date(from: "2017 01 01")!
let endDate = formatter.date(from: "2027 12 31")!
//-- how to set these "
1) Full calendar view
let parameters = ConfigurationParameters(startDate : startDate, endDate: endDate)
return parameters
2) for week view
let parameters = ConfigurationParameters(startDate : startDate, endDate: endDate, numberOfRows:1)
return parameters
}
func calendar( _ calendar: JTAppleCalendarView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell{
let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.dateLabel.text = cellState.text
configureCell(cell:cell, cellState: cellState)
return cell
}
//------------ selected item
func calendar( _ calendar: JTAppleCalendarView, didSelectDate date: Date, cell:JTAppleCell?, cellState:CellState){
configureCell(cell: cell, cellState: cellState)
}
func calendar( _ calendar: JTAppleCalendarView, didDeselectDate date: Date, cell:JTAppleCell?, cellState:CellState){
configureCell(cell: cell, cellState: cellState)
}
func calendar(_ calendar: JTAppleCalendarView, didScrollToDateSegmentWith visibleDates: DateSegmentInfo) {
setupCalendarView(dateSegment: visibleDates)
}
}
Please help.
Thanks
So the plan is:
You have a variable for the number of rows.
In a monthView mode, it has 6 rows.
In a weekView mode, it has 1 row.
So when you want to change the mode you change numberOfRows and reload calendarView and scroll to the current date.
Also when you have weekView, you should use a little bit different ConfigurationParameters.
That's how I do this:
#IBAction func monthWeekModeChanged(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
numberOfRows = 6
} else {
numberOfRows = 1
}
calendarView.reloadData()
calendarView.scrollToDate(Date(), animateScroll: false)
}
var numberOfRows = 6
extension CalendarViewController: JTAppleCalendarViewDataSource {
func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
let startDate = viewModel.formatter.date(from: "01-Jan-2019")
let endDate = viewModel.formatter.date(from: "31-Dec-2020")
if numberOfRows == 6 {
return ConfigurationParameters(startDate: startDate!, endDate: endDate!, numberOfRows: numberOfRows, firstDayOfWeek: .monday)
} else {
return ConfigurationParameters(startDate: startDate!,
endDate: endDate!,
numberOfRows: 1,
generateInDates: .forFirstMonthOnly,
generateOutDates: .off, firstDayOfWeek: .monday,
hasStrictBoundaries: false)
}
}
}
The tutorial here states just how to do this.
I cannot paste the whole thing here since the instructions are long.
Also, at the bottom of the page is the complete code in a zip file that you can play around with.

set alarm using DatePicker (swift3

My code below works that if you manually use to datePicker to match the date and time with the users date and time it will print cool. However the code does not work as a alarm. I can set the date picker ahead of the user time and when the user time matches the date pickers timer nothing prints. I just want to be able to select a date/time using date picker and when the users eventually matches the datePickers time just print cool.
import UIKit
var dateFormatter : DateFormatter!
let datePicker2 = UIDatePicker();
let date = Date()
class ViewController: UIViewController {
#IBOutlet var dateLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let datePicker : UIDatePicker = UIDatePicker(frame: CGRect(x: 0,y: 330,width: self.view.frame.size.width,height: 220))
datePicker.datePickerMode = UIDatePickerMode.dateAndTime
self.view.addSubview(datePicker)
datePicker.addTarget(self, action: #selector(ViewController.change(_:)), for: UIControlEvents.valueChanged)
dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd hh:mm"
}
#IBAction func change(_ sender : UIDatePicker)
{
let pickerString = dateFormatter.string(from: sender.date)
let nowString = dateFormatter.string(from: Date())
dateLabel.text = pickerString
if pickerString == nowString {
print("cool")
}
}}
This is happening because your if statement is only being called when the picker moves. You need a timer that fires every second looking to see if they match. To use the method below you just need to move the pickerString and nowString up to global variables. If you don't like that you can refactor and use as you want.
var pickerString: String?
var nowString: String?
override func viewDidLoad() {
super.viewDidLoad()
let _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
if pickerString == nowString {
print("cool")
}
}
#buildSucceeded

FSCalendar events in Swift 3

How can events be added to an FSCalendar in swift 3?
Implement the appropriate methods in a class adopting FSCalendarDataSource.
var datesWithEvent = ["2015-10-03", "2015-10-06", "2015-10-12", "2015-10-25"]
var datesWithMultipleEvents = ["2015-10-08", "2015-10-16", "2015-10-20", "2015-10-28"]
fileprivate lazy var dateFormatter2: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
let dateString = self.dateFormatter2.string(from: date)
if self.datesWithEvent.contains(dateString) {
return 1
}
if self.datesWithMultipleEvents.contains(dateString) {
return 3
}
return 0
}
Based On FsCalendar Documentation