我正在开发一个列出不同项目位置的项目,每个项目位置都与不同的时区相关联。我正在使用 FSCalendar 来显示当前所选项目在其时区的日期。我无法在 FSCalendar View 上正确显示日期。
我想在 FSCalendar View 上显示日期,无论设备中配置的时区如何。这意味着即使用户手动更改设备中的设置时区,此更改也不应影响我的项目日历。 (例如:通常在所有设备中都会选择自动时区)
要实现此目的,我必须使用所选项目时区配置 FSCalendar。
我尝试使用 DateFormatter() 将 Date() 转换为项目时区。 尝试过 DST 计算。
func isDateInProjectTimeZone() -> Bool {
if let projectTimeZone = AppUtils.timeZoneForProject() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
var calendar = Calendar.current
calendar.timeZone = projectTimeZone
return calendar.isDateInToday(Date().dateInProjectTimeZone())
}
return false
}
最佳答案
我能够使用 FSCalendar 通过以下步骤实现我的要求,如果有人遇到相同的情况,答案可能会很有用。
要更改 FSCalendar 时区,请按照以下步骤操作:
创建 FSCalendar 的自定义类并编写所需的初始化方法,如下所示。
import FSCalendar class XYZFSCalendar: FSCalendar { override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) if let projectTimeZone = <Set_Your_Time_Zone_Here> { self.setValue(projectTimeZone, forKey: "timeZone") self.perform(Selector(("invalidateDateTools"))) } } }
上面的代码使FSCalendar独立于系统时间
- 将 Storyboard 中的上述自定义日历指定为 FSCalendar 的自定义类
- 如果您向日历指定任何日期
例如:
import FSCalendar
class ViewController: UIVIewController {
@IBOutlet weak var calendar: XYZFSCalendar!
override func viewDidLoad() {
super.viewDidLoad()
//When you set the date below, the date will be displayed in the FSCalendar based on your custom timezone.
calendar.select = Date()
}
}
这对我的情况有所帮助,希望它也能帮助有需要的人。时区可能不会全局更改,但每次使用 FSCalendar 的预设时区实例化该类时,它都会起作用。
谢谢。
关于ios - 在项目中全局更改 FSCalendar 的时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58523548/