Swift 中的出现时包含在 [英] appearanceWhenContainedIn in Swift
问题描述
我正在尝试将我的应用程序转换为 Swift 语言.
I'm trying to convert my app to the Swift language.
我有这行代码:
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil]
setTitleTextAttributes:textDictionary
forState:UIControlStateNormal];
如何将其转换为 Swift?
How to convert it to Swift?
在 Apple 的文档中,没有这种方法.
推荐答案
iOS 9 更新:
如果您的目标是 iOS 9+(从 Xcode 7 b1 开始),UIAppearance
协议中有一个不使用可变参数的新方法:
Update for iOS 9:
If you're targeting iOS 9+ (as of Xcode 7 b1), there is a new method in the UIAppearance
protocol which does not use varargs:
static func appearanceWhenContainedInInstancesOfClasses(containerTypes: [AnyObject.Type]) -> Self
可以这样使用:
UITextField.appearanceWhenContainedInInstancesOfClasses([MyViewController.self]).keyboardAppearance = .Light
如果您仍需要支持 iOS 8 或更早版本,请使用以下对此问题的原始答案.
If you still need to support iOS 8 or earlier, use the following original answer to this question.
这些方法对 Swift 不可用,因为 Obj-C varargs 方法与 Swift 不兼容(参见 http://www.openradar.me/17302764).
These methods are not available to Swift because Obj-C varargs methods are not compatible with Swift (see http://www.openradar.me/17302764).
我编写了一个适用于 Swift 的非可变参数解决方法(我对 UIBarItem
重复了相同的方法,它不是从 UIView
继承而来):
I wrote a non-variadic workaround which works in Swift (I repeated the same method for UIBarItem
, which doesn't descend from UIView
):
// UIAppearance+Swift.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIView (UIViewAppearance_Swift)
// appearanceWhenContainedIn: is not available in Swift. This fixes that.
+ (instancetype)my_appearanceWhenContainedIn:(Class<UIAppearanceContainer>)containerClass;
@end
NS_ASSUME_NONNULL_END
——
// UIAppearance+Swift.m
#import "UIAppearance+Swift.h"
@implementation UIView (UIViewAppearance_Swift)
+ (instancetype)my_appearanceWhenContainedIn:(Class<UIAppearanceContainer>)containerClass {
return [self appearanceWhenContainedIn:containerClass, nil];
}
@end
请务必在您的桥接头中#import "UIAppearance+Swift.h"
.
Just be sure to #import "UIAppearance+Swift.h"
in your bridging header.
然后,从 Swift 调用(例如):
Then, to call from Swift (for example):
# Swift 2.x:
UITextField.my_appearanceWhenContainedIn(MyViewController.self).keyboardAppearance = .Light
# Swift 3.x:
UITextField.my_appearanceWhenContained(in: MyViewController.self).keyboardAppearance = .light
这篇关于Swift 中的出现时包含在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!