-3

我需要将此 Swift 代码翻译成 Objective-C。

animationView?.subviews
     .compactMap({ $0 as? RotatedView })
     .sorted(by: { $0.tag < $1.tag })
     .forEach { itemView in
         rotatedViews.append(itemView)
         if let backView = itemView.backView {
             rotatedViews.append(backView)
         }
     }

如果您无法转换为 Objective-C,请告诉我那里发生了什么,我会转换它。

PSrotatedView是类,UIView并且rotatedViews是一个空数组是rotatedView类。

正如@Haris Nadeem 所建议的那样,我正在分享我到目前为止所做的事情。

NSMutableArray *dummy = [[NSMutableArray alloc]init];
for(id view in self.animationView.subviews){
    if([view isKindOfClass:[RotatedView class]])
        [dummy addObject:(RotatedView *)view];
}
for(RotatedView *preView in dummy ){
//        if( view.tag>preView.tag){
//            [dummy addObject:view];
//            preView.tag=view.tag;
}
for( RotatedView *iteamView in [rotatedViews addObject:iteamView]){
     if (preView.backView ==  iteamView.backView)
         [rotatedViews addObject:preView.backView];
}
}
4

1 回答 1

1

我猜你没有给出这条线:var rotatedViews: [RotatedView]()

animationView?.subviews
   .compactMap({ $0 as? RotatedView })
   .sorted(by: { $0.tag < $1.tag })
   .forEach { itemView in
       rotatedViews.append(itemView)
       if let backView = itemView.backView {
           rotatedViews.append(backView)
       }
   }

让我们打破链接,并命名一些中间变量,因为在一行中这样做很酷,但有时更难调试,而且在 Objective-C 中,它会非常混乱 =>

let compacted = animationView?.subviews({ $0 as? RotatedView })
let sorted = compacted.sorted(by: { $0.tag < $1.tag })
sorted.forEach { itemView in
    rotatedViews.append(itemView)
    if let backView = itemView.backView {
        rotatedViews.append(backView)
    }
}

那么那里发生了什么:
compacted: 只保留属于 class 的子视图RotatedView
sorted: 我们根据它们的tag属性对这些视图进行排序。
在最后一个上,您完全误解了正在发生的事情。我们必须查看rotatedViews的所有先前视图sorted,如果它们有,backView我们也添加它。

未测试(在没有调试器/编译器/XCode 的情况下编写):

NSMutableArray *rotatedViews = [[NSMutableArray alloc] init]; //Final array

NSMutableArray *compacted = [[NSMutableArray alloc] init];
for (UIView *aView in animationView.subviews)
{
    if ([aView isKindOfClass:[RotatedView class]])
    {
        [compacted addObject:aView];
    }
}

NSArray *sorted = [compacted sortedArrayUsingComparator:^NSComparisonResult(RotatedView *view1, RotatedView *view2){
    NSInteger tag1 = [view1 tag];
    NSInteger tag2 = [view2 tag];
    return [@(tag1) compare:@(tag2)];
}];

for (RotatedView *itemView in sorted) //That's equivalent to forEach( itemView in
{
    [rotatedViews addObject:itemView]; //That's equivalent to rotatedViews.append(itemView)
    UIView *backView = [itemView backView]; //That's equivalent to if let backView = itemView.backView
    if (backView)  //That's equivalent to if let backView = itemView.backView
    {
        [rotatedViews addObject:backView]; //That's equivalent to rotatedViews.append(backView)
    }
}
于 2018-06-13T16:09:55.273 回答