在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
协议中有一种新方法,它不使用varargs:
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
请务必在您的桥接标题中#importUIAppearance + Swift.h
。
然后,从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屋!