1

我正在尝试将swift转换为objective-C。下面是我的代码:

迅速

import UIKit

protocol TraitCollectionOverridable {
    func preferredTraitCollection() -> UITraitCollection?
}

class CustomNavigationController: UINavigationController {
    override func overrideTraitCollectionForChildViewController(childViewController: UIViewController) -> UITraitCollection? {
        guard let conformingViewController = childViewController as? TraitCollectionOverridable else {
            return super.overrideTraitCollectionForChildViewController(childViewController)
        }

        return conformingViewController.preferredTraitCollection()
    }
}

Objective-C 头文件

@protocol TraitCollectionOverridable <NSObject>
- (UITraitCollection *) preferredTraitCollection;
@end

@interface CustomNavigationController : UINavigationController
@property (nonatomic, weak) id <TraitCollectionOverridable> traitsDelegate;
@end

.m 文件

@implementation CustomNavigationController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.traitsDelegate preferredTraitCollection];
    // Do any additional setup after loading the view.
}


- (UITraitCollection *)overrideTraitCollectionForChildViewController:(UIViewController *)childViewController
{
    if (CGRectGetWidth(self.view.bounds) < CGRectGetHeight(self.view.bounds)) {
        return [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassCompact];
    } else {
        return [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassRegular];
    }
}

@end

我的猜测是 overrideTraitCollectionForChildViewController 没有正确转换。对此的任何帮助都会很棒。

4

1 回答 1

1

我的猜测是 overrideTraitCollectionForChildViewController 没有正确转换。

Obj-C和Swift版本overrideTraitCollectionForChildViewController等价。这是更正后的代码:

对象-C

- (UITraitCollection *)overrideTraitCollectionForChildViewController:(UIViewController *)childViewController
{
    if( [childViewController conformsToProtocol:@protocol(TraitCollectionOverridable)] ) {
        return [(NSObject<TraitCollectionOverridable>*)childViewController preferredTraitCollection];
    } else {
        return [super overrideTraitCollectionForChildViewController:childViewController];
    }
}

迅速

override func overrideTraitCollectionForChildViewController(childViewController: UIViewController) -> UITraitCollection? {
    guard let conformingViewController = childViewController as? TraitCollectionOverridable else {
        return super.overrideTraitCollectionForChildViewController(childViewController)
    }

    return conformingViewController.preferredTraitCollection()
}
于 2015-07-10T03:51:06.903 回答