- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试从 this 开始快速制作日历很好的例子。到目前为止,我设法显示了网格和所有自定义 UICollectionViewLayout
的补充 View 。问题是当我试图在日历中添加事件时。日行和日历都在同一个 NSMutableDictionary
中,它有一个使用此格式 2016-10-12
表示日期(字符串)的键。 objective-c 代码是
-(void)groupEventsBySection{
//toDeviceTimezoneDateString simply take a Date and make a string
_eventsBySection = [mEvents groupBy:@"StartDate.toDeviceTimezoneDateString"].mutableCopy;
// after groupBy is performed _eventsBySection contains only those keys found in mEvents with inside an array of objects {
// "2016-10-12" = (
// "<MSEvent: 0x60000004a680>",
// "<MSEvent: 0x60000004a380>");
// "2016-10-13" = (
// "<MSEvent: 0x600000049b10>");
// "2016-10-17" = (
// "<MSEvent: 0x600000049fc0>");
// }
NSDate* date = [NSDate today:@"device"]; // today's date
if(self.daysToShow == 1 && _eventsBySection.count == 1){
date = [NSDate parse:_eventsBySection.allKeys.firstObject];
}
//here it adds the remaining "daysToShow" if the key doesn't already exist in the MutableDictionary.
for(int i = 0; i< self.daysToShow; i++){
if(![_eventsBySection.allKeys containsObject:date.toDeviceTimezoneDateString]){
[_eventsBySection setObject:@[] forKey:date.toDeviceTimezoneDateString];
}
date = [date addDay]; // this just add one day to date
}
}
到此为止已经很清楚了。问题是当我尝试更改 objective-c 中的 groupBy
函数时:
- (NSDictionary*)groupBy:(NSString*)keypath{
return [self groupBy:keypath block:^NSString *(id object, NSString *key) {
return key;
}];
}
- (NSDictionary*)groupBy:(NSString*)keypath block:(NSString*(^)(id object, NSString* key))block{
NSMutableDictionary *result = [NSMutableDictionary new];
NSString* finalKeypath = [NSString stringWithFormat:@"%@.@distinctUnionOfObjects.self",keypath];
NSArray *distinct = [self valueForKeyPath:finalKeypath];
[distinct each:^(NSString* value) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K = %@", keypath,value];
NSArray *objects = [self filteredArrayUsingPredicate:predicate];
[result setObject:objects forKey:block(objects[0],value)];
}];
return result;
}
- (NSDictionary*)expand:(NSString*)keypath{
return [self expand:keypath unique:NO];
}
到目前为止,这是我在 swift 中所做的:
我有这个类,在原始代码中是 MSEvent
class Event : NSObject {
var title:String?
var location:String?
var startTime:Date?
var endTime:Date?
var duration:Int?
var subtitle:String?
init(startTime: Date, duration: Int, title: String, subtitle: String) {
super.init()
self.startTime = startTime
self.duration = duration
self.title = title
self.subtitle = subtitle
}
我创建了一些假事件:
override func viewDidLoad() {
let today = Date()
let event1 = Event(startTime: today, duration: 60, title: "prova", subtitle: "HEllo")
let event2 = Event(startTime: today, duration: 60, title: "prova", subtitle: "HEllo")
let event3 = Event(startTime: today.dateByAddingDays(days: 1), duration: 60, title: "prova", subtitle: "HEllo")
var array:[Event] = []
array.append(event1)
array.append(event2)
array.append(event3)
calendarView.setEvents(events: array)
}
func setEvents(events:[Event]){
mEvents = events as NSArray
print(mEvents)
//this right now returns the 3 event objects I added:
// (
// "<myapp.Event: 0x60800032ba40>",
// "<myapp.Event: 0x60800032bae0>",
// "<myapp.Event: 0x60800032bcc0>"
// )
self.forceReload(reloadEvent: true) //force reload eventually call the groupEventsBy days
}
func groupEventsByDays(){
// of course everything works without the next line of code
eventsBySection = mEvents.groupBy(keypath: "startTime").mutableCopy() as! NSMutableDictionary
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var date = dateFormatter.date(from: "2016-10-01")
// right now daysToShow is equal to 30
for _ in 0..<daysToShow{
eventsBySection.setObject([], forKey: self.setFormatDate(date: date!) as NSCopying)
date = self.addDay(date: date!)
}
}
问题来了。这是我的扩展。 扩展 NSArray{
func groupBy(keypath:NSString)->NSDictionary{
return self.groupBy(keypath: keypath, block: { (object, key) -> NSString in
return key
})
}
func groupBy(keypath:NSString,block:@escaping ((_ object: Any, _ key:NSString )-> NSString))-> NSDictionary{
let result:NSMutableDictionary = NSMutableDictionary()
let finalKeypath = String.localizedStringWithFormat("%@.distinctUnionOfObjects.self", keypath)
let distinct:NSArray = self.value(forKey: finalKeypath) as! NSArray
(distinct as AnyObject).each(operation: { (value) in
let predicate = NSPredicate(format: "%K = %@", keypath,value as! CVarArg)
let objects = self.filtered(using: predicate)
result.setObject(objects, forKey: (block(objects[0], value as! NSString)))
})
return result;
}
func each(operation:@escaping ((_ object: AnyObject)-> Void)){
self.enumerateObjects({ (object, idx, stop) in
operation(object as AnyObject)
})
}
}
它崩溃并出现错误 此类不符合键 startTitle.distinctUnionOfObjects.self 的键值编码。'
我试过像这样使用 map
let startDate = array.map ({ $0.startTime })
我设法获取了所有日期(虽然没有明显区别),但我不知道如何使用 swift 实现上述代码中显示的相同结果。
最佳答案
我终于设法完成了上述 objective-c 代码使用 @distinctUnionOfObjects.sel
所做的事情。不过,我不太确定这是一种优雅的方式。欢迎所有评论或更好的答案。
extension Collection {
func find( predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Self.Iterator.Element? {
return try index(where: predicate).map({self[$0]})
}
}
override func viewDidLoad() {
super.viewDidLoad()
let event1 = Event(startTime: today!, duration: 60, title: "prova", subtitle: "HEllo")
let event2 = Event(startTime: (today?.dateByAddingDays(days: 5))!, duration: 60, title: "prova", subtitle: "HEllo")
let event3 = Event(startTime: (today?.dateByAddingDays(days: 1))!, duration: 60, title: "prova", subtitle: "HEllo")
let event4 = Event(startTime: todayLater!, duration: 60, title: "prova", subtitle: "HEllo")
var array:[Event] = []
array.append(event1)
array.append(event2)
array.append(event3)
array.append(event4)
// I create an array with all the date/startTime
let startTime = array.map ({ $0.startTime })
let dict:NSMutableDictionary = [:]
for date in startTime {
//find the objects for that date
let object = array.find(predicate: {$0.startTime?.toDeviceDateString() == date?.toDeviceDateString()})
//check if that key/date exist in the dictionary
if var val:[Event] = dict[(date?.setFormatDate())!] as! [Event]? {
//if it does I simply add the object to the array
val.append(object!)
dict.setObject(val, forKey: date?.setFormatDate() as! NSCopying)
} else {
print("key is not present in dict")
//otherwise I add a new array with that object inside for the date/key
dict.setObject([object], forKey: date?.setFormatDate() as! NSCopying)
}
}
calendarView.setEvents(events: dict)
}
func setEvents(events:NSMutableDictionary){
//slots events hold the events objects
slotEvents = events
self.forceReload(reloadEvent: true)
}
func groupEventsByDays(){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var date = dateFormatter.date(from: "2016-10-01")
for _ in 0..<daysToShow{
if let val:[Event] = slotEvents[(date?.setFormatDate())!] as! [Event]? {
eventsBySection.setObject(val, forKey: date?.setFormatDate() as! NSCopying)
}else{
eventsBySection.setObject([], forKey: date?.setFormatDate() as! NSCopying)
}
date = self.addDay(date: date!)
}
print("after\(eventsBySection)")
//Which print
//{
//"2016-10-01" = (
// );
//"2016-10-02" = (
// );
// "2016-10-03" = (
// "Optional(<myapp.Event: 0x6000001242e0>)",
// "<myapp.Event: 0x6000001242e0>"
// );
// "2016-10-04" = (
// "Optional(<myapp.Event: 0x600000124600>)"
// );
// "2016-10-05" = (
// );
// "2016-10-06" = (
// );
// "2016-10-07" = (
// );
// "2016-10-08" = (
// "Optional(<myapp.Event: 0x600000124240>)"
// );
// "2016-10-09" = (
// );
//.... and so on up to 30 days
}
关于swift - @distinctUnionOfObjects 在 Swift 中可用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39994134/
如何检测当前网络中计算机是否已连接/可用。 当然,它有多种用途,但我主要关心的是我的应用程序使用位于特定计算机中的资源,如果这些资源不可用,它甚至不会尝试连接,而是使用本地资源。 最佳答案 您可以尝试
雅虎建议load scripts at the bottom of an HTML pages出于性能原因。我使用遵守规则的 HTML5 Boilerplate。 这种方法的问题是 jQuery 也是
我有一个场景,我需要只向管理员而不是普通用户展示一个组件。 说, // This component should be rendered for public users.
我有一个数组,比方说 ["a","b","c"],我想把它变成一个对象,它以数组值作为键和一个默认值我可以设置。因此,如果默认值为 true,我希望我的输出为 {a:true, b:true, c:t
我假设在函数中创建一个新的 PS-Drive 会使该驱动器只能在该函数中访问。 如何通过从该函数可访问的 MAIN 调用函数来创建 PS 驱动器? $temproraryPSDriveName =
您会推荐哪些 .net 控制库作为企业必备的? 可以免费/非免费 至少应该包含一个真正强大的Datagrid Ajax 功能 有没有可用的比较? 最佳答案 我用过 Telerik ASP.NET控制之
假设我有一些像这样的 html: Hello World Javascript代码: var fooBar = document.getElementById('fooBar'); fooBar.
开始实现 camera plugin 时出现以下错误在我的 flutter 应用程序上: [VERBOSE-2:dart_error.cc(16)] Unhandled exception:
我想知道应该在哪里正确放置 countA,因为我希望将计数添加到所做的每个按钮中。开头的“count”变量用于制作新按钮,“countA”是我试图声明的计数,但它无法编译。这是我的代码片段:我的问题再
在python帮助文档中我经常看到带有函数名和命名参数的签名行,然后你会看到**kwarg(关键字参数)。 list? 打印到帮助文档字符串: Init signature: list(self, /
我是 UWP 的新手,想知道“Flyout”、“ContextFlyout”和“Popup”之间的区别。另外,我想知道“AppBar”和“CommandBar”之间的区别。我相信这些是容纳菜单或菜单项
我想显示可用的 Wifi 设备列表。这是我的代码,我不明白这里有什么错误: wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); i
这是我的代码: Random = function(name) { this.name = name; this.addSomething = function(a, b) {
我希望我的按钮持续动画直到用户触摸它,这是代码 func animate() { UIView.animateWithDuration(1, animations: { () -> Void
我正在为我正在参加的类(class)制作一个 HTTP 服务器作为项目,一周来我一直在尝试寻找解决方案。我有一个 DataInputStream,我需要等待客户端向我发送 http 请求,由于连接保持
我想创建一个 bash 脚本来检查我的 Linux 服务器中的哪些端口已关闭且未在特定范围(端口范围 (3000-3010))中使用。 打印输出只需1个端口,如果将输出保存为变量或保存在同一个文件中,
我写了一个我认为是最小的自定义设备来测试我对 QOM 和 QEMU 的总体理解。以下是省略注释的相关代码。不幸的是,当我启动 guest 并将我的设备名称作为命令行参数传递时,它无法找到我的设备并退出
调用Opencv函数时,通常会提供一个常量给函数调用,如: im_hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) 虽然我找不到对所有可用常量的引用。 Opencv
C++ 于 1998 年正式标准化,但我们能在多久以前找到一个名为 string 的类,它看起来像 C++2003 中的 std::string预标准 C++ 实现? 我问是因为 CString 作为
是否有一个官方的(或可能没有)git 命令列表,--porcelain 选项可用?或者我应该在 the porcelain commands list 中手动查看它们中的每一个吗? ? 我已经设法用谷
我是一名优秀的程序员,十分优秀!