简体   繁体   English

UISegment Control - 根据天选择设置 (SWIFT)

[英]UISegment Control - Set selected according to day (SWIFT)

Like the title says, I'm trying to set the selected segment control according to day.正如标题所说,我正在尝试根据日期设置选定的段控件。 My segment control includes the days of the week and i also have a date and time label.我的段控制包括星期几,我还有一个日期和时间标签。 The proper day has to be selected when the view is open打开视图时必须选择正确的日期

I know i have to do something with:我知道我必须做一些事情:

segmentControl.selectedSegmentIndex = 0

I'm getting the date with:我得到的日期是:

showDate.text = "Date:  " + DateFormatter.localizedString(from: Date(), dateStyle: DateFormatter.Style.medium, timeStyle: .none)

But I'm not sure how to set the selectedIndex to be dependent on date and show the appropriate day.但我不确定如何将 selectedIndex 设置为依赖于日期并显示适当的日期。 I'm still new to swift and still learning, any help will be very much appreciated!我仍然是 swift 的新手并且仍在学习,任何帮助将不胜感激! Thanks谢谢

UISegmentedControl indexes start from 0. If you have all the days of the week in it its indexes start from 0 and end in 6. UISegmentedControl索引从 0 开始。如果你有一周中的所有日子,它的索引从 0 开始,以 6 结束。

You can get a day's index in weekdays using this您可以使用它在工作日获得一天的索引

let day = Calendar.current.component(.weekday, from: Date())

this returns 1 for Sunday, 2 for Monday... 7 for Saturday这返回 1 周日,2 周一... 7 周六

So you can assign selectedSegmentIndex as follows所以你可以分配selectedSegmentIndex如下

    if (2...6).contains(day) {
        segmentControl.selectedSegmentIndex = day-2
    } else {
        segmentControl.selectedSegmentIndex = UISegmentedControlNoSegment
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM