Why is my drag to select function selecting the entire calendar and not what’s within the bounds?

I am trying to create a calendar view that allows users to select multiple date ranges, including non continuous, continuous, and single dates. I also want to allow users to drag to select date ranges but I am struggling to implement that portion.

I believe the issue is my if statement in the dragSelect function, the original from this thread is commented out below it. I’ve tried using DispatchQueue to see if async timing was the problem but I might have done that wrong, it also seems like rectangles.content[i] = gp.frame(in: .named("container")) could be the problem?. getBackground just sets the background to a certain color if it is contained in the selectedDates set. Any advice is greatly appreciated!!

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>struct testDrag: View
{
var rectangles = Rectangles()
@State var selectRect: CGRect?
let days = Date.now.calendarDisplayDays
@State private var date = Date.now
private var textColor: Color = .black
private var selectColor: Color = .baseTeal
let daysOfWeek = Date.capitalizedFirstLettersOfWeekdays
let columns = Array(repeating: GridItem(.flexible()), count: 7)
@State private var selectedDates: Set<Date> = []
@State private var selectedCell: CGRect?
var body: some View
{
GeometryReader { geometry in
ZStack(alignment: .topLeading) {
LazyVGrid(columns: columns
,content: {
ForEach(0..<days.count, id: .self) { i in
if days[i].monthInt != date.monthInt {
Text("")
.frame(maxWidth: geometry.size.width/7, minHeight: 40, alignment: .center)
} else {
Text(days[i].formatted(.dateTime.day()))
.fontWeight(.medium)
.frame(minWidth: (geometry.size.width/7) - 3, minHeight: 40, alignment: .center)
.background(getBackground(for: days[i]))
.background() {
GeometryReader { gp -> Color in
rectangles.content[i] = gp.frame(in: .named("container"))
return Color.clear
}
}
.cornerRadius(20)
.onTapGesture {
if selectedDates.contains(days[i].startOfDay) {
selectedDates.remove(days[i].startOfDay)
}
else {
selectedDates.insert(days[i].startOfDay)
}
}
.foregroundColor(
selectedDates.contains(days[i].startOfDay) ? textColor :
(Date.now.startOfDay == days[i].startOfDay ? selectColor : textColor)
)
}
}
})
.coordinateSpace(name: "container")
.gesture(dragSelect)
if let selR = selectRect {
Rectangle()
.frame(width: selR.width, height: selR.height)
.offset(x: selR.origin.x, y: selR.origin.y)
}
}
}
}
private var dragSelect: some Gesture
{
DragGesture(minimumDistance: 2)
.onChanged { drag in
let a = drag.startLocation
let b = drag.location
self.selectRect = CGRect(x: min(a.x, b.x), y: min(a.y, b.y), width: abs(a.x - b.x), height: abs(a.y - b.y))
var resSet = Set<Date>()
for i in 0 ..< self.days.count {
if let rect = self.rectangles.content[i], ((self.selectRect?.intersects(rect)) != nil) {
// if CGRectIntersectsRect(rectangles.content[i]!, selectRect!) {
resSet.insert(days[i])
}
self.selectedDates = resSet
}
}
.onEnded { _ in
self.selectRect = nil
}
}
}
class Rectangles
{
var content = [Int : CGRect]()
}
</code>
<code>struct testDrag: View { var rectangles = Rectangles() @State var selectRect: CGRect? let days = Date.now.calendarDisplayDays @State private var date = Date.now private var textColor: Color = .black private var selectColor: Color = .baseTeal let daysOfWeek = Date.capitalizedFirstLettersOfWeekdays let columns = Array(repeating: GridItem(.flexible()), count: 7) @State private var selectedDates: Set<Date> = [] @State private var selectedCell: CGRect? var body: some View { GeometryReader { geometry in ZStack(alignment: .topLeading) { LazyVGrid(columns: columns ,content: { ForEach(0..<days.count, id: .self) { i in if days[i].monthInt != date.monthInt { Text("") .frame(maxWidth: geometry.size.width/7, minHeight: 40, alignment: .center) } else { Text(days[i].formatted(.dateTime.day())) .fontWeight(.medium) .frame(minWidth: (geometry.size.width/7) - 3, minHeight: 40, alignment: .center) .background(getBackground(for: days[i])) .background() { GeometryReader { gp -> Color in rectangles.content[i] = gp.frame(in: .named("container")) return Color.clear } } .cornerRadius(20) .onTapGesture { if selectedDates.contains(days[i].startOfDay) { selectedDates.remove(days[i].startOfDay) } else { selectedDates.insert(days[i].startOfDay) } } .foregroundColor( selectedDates.contains(days[i].startOfDay) ? textColor : (Date.now.startOfDay == days[i].startOfDay ? selectColor : textColor) ) } } }) .coordinateSpace(name: "container") .gesture(dragSelect) if let selR = selectRect { Rectangle() .frame(width: selR.width, height: selR.height) .offset(x: selR.origin.x, y: selR.origin.y) } } } } private var dragSelect: some Gesture { DragGesture(minimumDistance: 2) .onChanged { drag in let a = drag.startLocation let b = drag.location self.selectRect = CGRect(x: min(a.x, b.x), y: min(a.y, b.y), width: abs(a.x - b.x), height: abs(a.y - b.y)) var resSet = Set<Date>() for i in 0 ..< self.days.count { if let rect = self.rectangles.content[i], ((self.selectRect?.intersects(rect)) != nil) { // if CGRectIntersectsRect(rectangles.content[i]!, selectRect!) { resSet.insert(days[i]) } self.selectedDates = resSet } } .onEnded { _ in self.selectRect = nil } } } class Rectangles { var content = [Int : CGRect]() } </code>
struct testDrag: View
{
    var rectangles = Rectangles()
    @State var selectRect: CGRect?
    let days = Date.now.calendarDisplayDays
    @State private var date = Date.now
    private var textColor: Color = .black
    private var selectColor: Color = .baseTeal
    let daysOfWeek = Date.capitalizedFirstLettersOfWeekdays
    let columns = Array(repeating: GridItem(.flexible()), count: 7)
    
    @State private var selectedDates: Set<Date> = []
    @State private var selectedCell: CGRect?
    var body: some View
    {
        GeometryReader { geometry in
            ZStack(alignment: .topLeading) {
                LazyVGrid(columns: columns
                          ,content: {
                    ForEach(0..<days.count, id: .self) { i in
                        if days[i].monthInt != date.monthInt {
                            Text("")
                                .frame(maxWidth: geometry.size.width/7, minHeight: 40, alignment: .center)
                        } else {
                            Text(days[i].formatted(.dateTime.day()))
                                .fontWeight(.medium)
                                .frame(minWidth: (geometry.size.width/7) - 3, minHeight: 40, alignment: .center)
                                .background(getBackground(for: days[i]))
                            
                                .background() {
                                    GeometryReader { gp -> Color in
                                        rectangles.content[i] = gp.frame(in: .named("container"))
                                        
                                        return Color.clear
                                    }
                                }
                            
                                .cornerRadius(20)
                                .onTapGesture {
                                    if selectedDates.contains(days[i].startOfDay) {
                                        selectedDates.remove(days[i].startOfDay)
                                    }
                                    else {
                                        selectedDates.insert(days[i].startOfDay)
                                    }
                                }
                                .foregroundColor(
                                    selectedDates.contains(days[i].startOfDay) ? textColor :
                                        (Date.now.startOfDay == days[i].startOfDay ? selectColor : textColor)
                                )
                        }
                    }
                })
                .coordinateSpace(name: "container")
                .gesture(dragSelect)
                
                if let selR = selectRect {
                    Rectangle()
                        .frame(width: selR.width, height: selR.height)
                        .offset(x: selR.origin.x, y: selR.origin.y)
                }
            }
        }
    }
    
    private var dragSelect: some Gesture
    {
        DragGesture(minimumDistance: 2)
            .onChanged { drag in
                    let a = drag.startLocation
                    let b = drag.location
                    
                    self.selectRect = CGRect(x: min(a.x, b.x), y: min(a.y, b.y), width: abs(a.x - b.x), height: abs(a.y - b.y))
                    
                    var resSet = Set<Date>()
                    for i in 0 ..< self.days.count {
                        if let rect = self.rectangles.content[i], ((self.selectRect?.intersects(rect)) != nil) {
                        // if CGRectIntersectsRect(rectangles.content[i]!, selectRect!) {

                            resSet.insert(days[i])
                            
                        }
                    self.selectedDates = resSet
                }
            }
            .onEnded { _ in
                    self.selectRect = nil
            }
    }
}

class Rectangles
{
    var content = [Int : CGRect]()
}

New contributor

machigai is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật