HStack {
ForEach(days, id:\.self) { day in
Text(day)
.font(.system(size: 12, weight: .medium))
.frame(maxWidth: .infinity)
}
}
LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 7), spacing: 20) {
ForEach(fetchDates()) { value in
ZStack {
if value.day != -1 {
let hasAppts = manager.days.contains(value.date.monthDayYearFormat())
NavigationLink(value: AppRouter.day(date: value.date)) {
Text("\(value.day)")
.foregroundColor(hasAppts ? .blue : .black)
.fontWeight(hasAppts ? .bold : .none)
.background {
ZStack(alignment: .bottom) {
Circle()
.frame(width: 48, height: 48)
.foregroundColor(hasAppts ? .blue.opacity(0.1) : .clear)
if value.date.monthDayYearFormat() == Date().monthDayYearFormat() {
Circle()
.frame(width: 8, height: 8)
.foregroundColor(hasAppts ? .blue : .gray)
}
}
}
}
.disabled(!hasAppts)
} else {
Text("")
}
}
.frame(width: 32, height: 32)
}
}
}
.padding()
}
Post
Replies
Boosts
Views
Activity
I embedded a vertical scrollview to a calendar that was originally horizontally navigation with buttons. But its isn't scrolling changing months. What am I missing?
let days = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"]
@State private var selectedMonth = 0
@State private var selectedDate = Date()
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
ScrollView {
VStack {
Rectangle()
.frame(height: 1)
.foregroundColor(.gray)
VStack(spacing: 20) {
// Month Selection
HStack {
Spacer()
Button {
withAnimation {
selectedMonth -= 1
}
} label: {
Image(systemName: "lessthan.circle.fill")
.resizable()
.scaledToFit()
.frame(width: 32, height: 32)
.foregroundColor(.gray)
}
Spacer()
Text(selectedDate.monthYearFormat())
.font(.title2)
Spacer()
Button {
withAnimation {
selectedMonth += 1
}
} label: {
Image(systemName: "greaterthan.circle.fill")
.resizable()
.scaledToFit()
.frame(width: 32, height: 32)
.foregroundColor(.gray)
}
Spacer()
}
HStack {
ForEach(days, id:\.self) { day in
Text(day)
.font(.system(size: 12, weight: .medium))
.frame(maxWidth: .infinity)
}
}
LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 7), spacing: 20) {
ForEach(fetchDates()) { value in
ZStack {
if value.day != -1 {
let hasAppts = manager.days.contains(value.date.monthDayYearFormat())
NavigationLink(value: AppRouter.day(date: value.date)) {
Text("\(value.day)")
.foregroundColor(hasAppts ? .blue : .black)
.fontWeight(hasAppts ? .bold : .none)
.background {
ZStack(alignment: .bottom) {
Circle()
.frame(width: 48, height: 48)
.foregroundColor(hasAppts ? .blue.opacity(0.1) : .clear)
if value.date.monthDayYearFormat() == Date().monthDayYearFormat() {
Circle()
.frame(width: 8, height: 8)
.foregroundColor(hasAppts ? .blue : .gray)
}
}
}
}
.disabled(!hasAppts)
} else {
Text("")
}
}
.frame(width: 32, height: 32)
}
}
}
.padding()
}
}
.navigationDestination(for: AppRouter.self) { router in
switch router {
case .day(let date):
DayView(path: $path, currentDate: date)
.environmentObject(manager)
case .booking(let date):
BookingView(path: $path, currentDate: date)
.environmentObject(manager)
case .confirmation(let date):
ConfirmationView(path: $path, currentDate: date)
}
}
.frame(maxHeight: .infinity, alignment: .top)
.onChange(of: selectedMonth) { _ in
selectedDate = fetchSelectedMonth()
}
}
}
func fetchDates() -> [CalendarDate] {
let calendar = Calendar.current
let currentMonth = fetchSelectedMonth()
var dates = currentMonth.datesOfMonth().map({ CalendarDate(day: calendar.component(.day, from: $0), date: $0) })
let firstDayOfWeek = calendar.component(.weekday, from: dates.first?.date ?? Date())
for _ in 0..<firstDayOfWeek - 1 {
dates.insert(CalendarDate(day: -1, date: Date()), at: 0)
}
return dates
}
func fetchSelectedMonth() -> Date {
let calendar = Calendar.current
let month = calendar.date(byAdding: .month, value: selectedMonth, to: Date())
return month!
}
}
Not sure what Im doing wrong here. Says "Cannot convert value of type 'String' to expected argument type 'Int'".
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "calCell", for: indexPath) as! CalendarCell
cell.dayOfMonth.text = totalSquares[indexPath.item]
//show the weekend days in different color
switch indexPath.item {
case 0,6,7,13,14,20,21,27,28,34,35,41:
if Int(cell.dayOfMonth.text = "\(indexPath.item)" > 0 {
cell.dayOfMonth.textColor = UIColor.lightGray
}
default:
break
}
return cell
}
I have a ViewController that calls a Xib view to popup (as a PressentationController). I need to put a single cell collectonview on that Xib view. How can I go about doing that because I cannot embed a collectionview in a Xib via storyboard. Is there a way to do that programmatically?
I have a collectionview of UILabels.
when you tap a cell it should display its detail onto a pop up modal view.
How do you display it onto that modal view in the same View controller?
2a. How can you cycle (loop) a group of arrays via UILabel forward and backwards in cells?
2b. How do you filter the arrays so that it always shows with a specific cell? (eg: Cell 2 will always have "D, E, F" when scrolling through)
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return totalSquares.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "calCell", for: indexPath) as! CalendarCell
cell.dayOfMonth.text = totalSquares[indexPath.item]
return cell
}
// Cell 1 Cell 2 Cell 3
let myArray: String = [[" A, B, C"], ["D, E, F"], ["G, H, I"]] etc..
I've added long press programmatically but it does nothing.
What am I doing wrong? Thanks in advance.
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIGestureRecognizerDelegate {
@IBOutlet weak var monthLabel: UILabel!
@IBOutlet weak var collectionView: UICollectionView!
var selectedDate = Date()
var totalSquares = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setCellView()
setMonthView()
func setupLongGestureRecognizerOnCollection() {
let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gestureRecognizer:)))
longPressedGesture.minimumPressDuration = 0.5
longPressedGesture.delegate = self
longPressedGesture.delaysTouchesBegan = true
collectionView?.addGestureRecognizer(longPressedGesture)
}
}
func setCellView() {
let width = (collectionView.frame.size.width - 2) / 8
let height = (collectionView.frame.size.height - 2) / 8
let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.itemSize = CGSize(width: width, height: height)
}
func setMonthView(){
totalSquares.removeAll()
let daysInMonth = CalendarHelper().daysInMonth(date: selectedDate)
let firstDayOfMonth = CalendarHelper().firstOfMonth(date: selectedDate)
let startingSpaces = CalendarHelper().weekDay(date: firstDayOfMonth)
var count: Int = 1
while(count <= 42) {
if(count <= startingSpaces || count - startingSpaces > daysInMonth)
{
totalSquares.append("")
}
else
{
totalSquares.append(String(count - startingSpaces))
}
count += 1
}
monthLabel.text = CalendarHelper().monthString(date: selectedDate) + " " + CalendarHelper().yearString(date: selectedDate)
collectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return totalSquares.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "calCell", for: indexPath) as! CalendarCell
cell.dayOfMonth.text = totalSquares [indexPath.item]
return cell
}
@objc func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
if (gestureRecognizer.state != .began) {
return
}
let p = gestureRecognizer.location(in: collectionView)
if let indexPath = collectionView?.indexPathForItem(at: p) {
print("Long press at item: \(indexPath.row)")
}
}
@IBAction func previousMonthButton(_ sender: Any) {
selectedDate = CalendarHelper().minusMonth(date: selectedDate)
setMonthView()
}
@IBAction func nextMonthButton(_ sender: Any) {
selectedDate = CalendarHelper().plusMonth(date: selectedDate)
setMonthView()
}
override open var shouldAutorotate: Bool {
return false
}
}
The GitHub source is here:
github.com/codeWithCal/CalendarExampleTutorial
Im trying to extract the IP address that is nested in html and print it out to a string.<ul> <li>IP Address: <span class="darktext">199.123.456.789</span> </li> <li>Internet Service Provider: <span class="darktext">Optimum WiFi</span> </li> <li>City: <span class="darktext">My City</span> </li> <li>State/Region: <span class="darktext">New City</span> </li> <li>Country: <span class="darktext">United States</span> </li> <li>Browser: <span class="darktext">TextFromURL</span> </li> <li>Operating System: <span class="darktext"></span> </li> <li>Screen Resolution: <span id="resolution" class="darktext"></span> </li> </ul>
Im trying to have a swipe func showing an array of images using a "For In Loop". The images and data that I want presented separately in a UIView for the images and and a few UILabels for the car information. Im getting stuck of how to extract the images "name" and putting them in the "for in" loop. Nothing seems to be working.import UIKit
struct ExoticCars {
let name: UIImage;
let make: String;
let model: String;
let year: Int;
let topSpeed: Double;
let price: Int;
class ViewController: UIViewController {
@IBOutlet weak var imageVIew: UIImageView!
@IBOutlet weak var makeLabel: UILabel!
@IBOutlet weak var modelLabel: UILabel!
@IBOutlet weak var yearLabel: UILabel!
@IBOutlet weak var speedLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
var index = 0
var exoticCar: [ExoticCars] = [
ExoticCars(name: imageLiteral(resourceName: "porsche_spyder"), make: "Porsche", model: "918 Spyder", year: 2015, topSpeed: 2.2, price: 931_975),
ExoticCars(name: imageLiteral(resourceName: "tesla_p"), make: "Tesla", model: "Model S P100D", year: 2019, topSpeed: 2.28, price: 121_190),
ExoticCars(name: imageLiteral(resourceName: "dodge_challenger"), make: "Dodge", model: "Challenger SRT", year: 2018, topSpeed: 2.3, price: 86_090),
ExoticCars(name: imageLiteral(resourceName: "ferrari_laferrari"), make: "Ferrari", model: "LaFerrari", year: 2019, topSpeed: 2.4, price: 2_200_000),
ExoticCars(name: imageLiteral(resourceName: "bugatti_chiron"), make: "Bugatti", model: "Chiron", year: 2019, topSpeed: 2.5, price: 3_000_000),
ExoticCars(name: imageLiteral(resourceName: "rimac_concept1"), make: "Rimac", model: "Concept One", year: 2018, topSpeed: 1.85, price: 1_200_000),
ExoticCars(name: imageLiteral(resourceName: "mclaren_720s"), make: "McLaren", model: "720s", year: 2019, topSpeed: 2.0, price: 299_000),
ExoticCars(name: imageLiteral(resourceName: "porsche_gt2"), make: "Porsche", model: "911 GT2 RS", year: 2018, topSpeed: 2.6, price: 294_450),
ExoticCars(name: imageLiteral(resourceName: "lamborghini_aventador"), make: "Lamborghini", model: "Aventador LP", year: 2016, topSpeed: 2.7, price: 497_895),
ExoticCars(name: imageLiteral(resourceName: "koenigsegg"), make: "Koenigsegg", model: "Regera", year: 2017, topSpeed: 2.8, price: 2_000_000),
];
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var name = [UIView]()
for name in exoticCar {
}
}
@IBAction func swipeLeft(_ sender: UISwipeGestureRecognizer) {
if name < exoticCar.count - 1 {
index = index + 1
}
}
@IBAction func swipeRight(_ sender: UISwipeGestureRecognizer) {
if index < exoticCar.count + 1 {
index = index - 1
}
}
}
}
How can I customize an UIDatePicker to show: mm:dd:yyyy and the time with only two options to choose from: hh1 or hh2: (07) hrs or (22)hrs?example: (scrollable) Date: May 23 2020 Time: 0700 (option 1) 2200 (option 2)
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gesture:)))
calendarView.addGestureRecognizer(longPressGesture)
}
@objc func handleLongPress(gesture: UILongPressGestureRecognizer) {
guard gesture.state == .began else {return}
let position = gesture.location(in: collectionView)
if let indexPath = collectionView.indexPathForItem(at: position) {
guard let modalCalVC = self.storyboard?.instantiateViewController(identifier: "ModalCalViewController") as? ModalCalViewController else {
print("ModalCalViewController cannot be instantiated")
return
}
let value = true //Get the value you want to pass from `indexPath`
modalCalVC.passedValue = value
present(modalCalVC, animated: true, completion: nil)
} else {
print("Long press not on a cell")
}
}I dont understand why it crashes I get Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file.swift, Line 10
I have a collection view (Calendar) and I have my modal view and I want the modal view to display what is in the cell when its selected.Im not sure how do I go about doing this?So far I changed the color of the cells background when selected.How do I call and animate the child view controller?and then display that cells content?// Reuseable Cell
setupViews()
myCollectionView.delegate=self
myCollectionView.dataSource=self
myCollectionView.register(dateCVCell.self, forCellWithReuseIdentifier: "Cell")
}// cell selected BG color change
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell=collectionView.cellForItem(at: indexPath)
cell?.backgroundColor=Colors.blue
let lbl = cell?.subviews[1] as! UILabel
lbl.textColor=UIColor.white
}
Im trying to make a generated array of (6) numbers display per cell, of a collection view with reusable cells.The array is being generated with this:let original = [1, 2, 3, 4, 5, 6]
var currentArray = original
print("currentArray =", currentArray)
var stop = false
repeat {
currentArray = currentArray.map() { ($0 + 2) % 25 + 1}
print("currentArray =", currentArray)
stop = currentArray[0] == 25
} while !stopmy Collection View is being setup here...<ViewController.swift>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell=collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! discoCueCell
cell.backgroundColor=UIColor.clearAny ideas???
I have one issue that I can utilize in either of two way...**Problem**So... Im trying to get and array (set) of 6 integers to cycle (loop) itself from numbers 1 - 25, but when it reaches 25 start back at 1 and continue the loop. (pretty easy)**Restraints/Condition**The conditions are that I have to reuse the last three number of the first array and have those three start the next set of six integers.Solution #1the last three incremented by +1 then start the next 6:[1, 2, 3, 4, 5, 6, ] [4, 5, 6, 7, 8, 9,] [7, 8, 9, 10, 11, 12,] [10, 11, 12, 13, 14, 15,] Etc...Solution #2Just have the block of arrays repeat itself to so that it appears to be incrementing:[1, 2, 3, 4, 5, 6, ] [4, 5, 6, 7, 8, 9,] [7, 8, 9, 10, 11, 12,] [10, 11, 12, 13, 14, 15,] [13, 14, 15, 16, 17, 18,] [16, 17, 18, 19, 20, 21,][19, 20, 21, 22, 23, 24,] [22, 23, 24, 25, 1, 2,] .... until it repeats itself back to: [1, 2, 3, 4, 5, 6, ]I dont even know how or where to start programmatically. Thanks for your help.
Im trying to use this line of code:func getFirstWeekDay() -> Int { let day = ("\(currentYear)-\(currentMonthIndex)-01".date?.firstDayOfTheMonth.weekday)! return day }but Im getting this error.. I dont know how else to write it.Error: Cannot use optional chaining on non-optional value of type 'Any'