我的appDelegate中的以下代码适用于Objective-C,以显示自定义UITabBar项的选定状态。尽管我已经尽了最大的努力,但我仍无法弄清楚如何将此代码转换为Swift。有人可以指出我正确的方向吗?

UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
UITabBar *tabBar = tabBarController.tabBar;
UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];
UITabBarItem *tabBarItem4 = [tabBar.items objectAtIndex:3];

[[UITabBar appearance] setTintColor:[UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0]]; //make all text and icons in tab bar the system blue font
tabBarItem1.selectedImage = [UIImage imageNamed:@"815-car-selected@2x.png"];
tabBarItem2.selectedImage = [UIImage imageNamed:@"742-wrench-selected@2x.png"];
tabBarItem3.selectedImage = [UIImage imageNamed:@"710-folder-selected@2x.png"];
tabBarItem4.selectedImage = [UIImage imageNamed:@"724-info-selected@2x.png"];

谢谢。

最佳答案

我建议仅查看XCode中的文档。所有文档都是用Swift和Objective C编写的,因此在两种语言之间进行翻译非常容易。另请阅读Apple的快速基础知识,以更好地理解此代码翻译:https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_467

翻译:

// Type casting in swift is "as Type"
tabBarController = self.window.rootViewController as UITabBarController
tabBar = tabBarController.tabBar
// Retrieving array values at indices can be shortened as array[index]
tabBarItem1 = tabBar.items[0] as UITabBarItem
tabBarItem2 = tabBar.items[1] as UITabBarItem
tabBarItem3 = tabBar.items[2] as UITabBarItem
tabBarItem4 = tabBar.items[3] as UITabBarItem

// The UIColor method you are using is an initializer in swift
tabBar.barTintColor = UIColor(red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0)

// UIImage also has an initializer for your situation in swift
tabBarItem1.selectedImage = UIImage(named: "815-car-selected@2x.png")
tabBarItem2.selectedImage = UIImage(named: "742-wrench-selected@2x.png")
tabBarItem3.selectedImage = UIImage(named: "710-folder-selected@2x.png")
tabBarItem4.selectedImage = UIImage(named: "724-info-selected@2x.png")

10-07 19:49
查看更多