使用关联对象
当你想要向需要保持状态的现有类添加功能时,关联对象非常有用。
例如,向每个 UIView 添加一个活动指示器:
Objective-C 实施
#import <objc/runtime.h>
static char ActivityIndicatorKey;
@implementation UIView (ActivityIndicator)
- (UIActivityIndicatorView *)activityIndicator {
return (UIActivityIndicatorView *)objc_getAssociatedObject(self, &ActivityIndicatorKey);
}
- (void)setActivityIndicator: (UIActivityIndicatorView *)activityIndicator {
objc_setAssociatedObject(self, &ActivityIndicatorKey, activityIndicator, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)showActivityIndicator {
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleGray];
[self setActivityIndicator:activityIndicator];
activityIndicator.center = self.center;
activityIndicator.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
[activityIndicator startAnimating];
[self addSubview: activityIndicator];
}
- (void)hideActivityIndicator {
UIActivityIndicatorView * activityIndicator = [self activityIndicator];
if (activityIndicator != nil) {
[[self activityIndicator] removeFromSuperview];
}
}
@end
你还可以通过 Swift 访问 Objective-C 运行时:
SWIFT 代码
extension UIView {
private struct AssociatedKeys {
static var activityIndicator = "UIView.ActivityIndicatorView"
}
private var activityIndicatorView: UIActivityIndicatorView? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.activityIndicator) as? UIActivityIndicatorView
}
set (activityIndicatorView) {
objc_setAssociatedObject(self, &AssociatedKeys.activityIndicator, activityIndicatorView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func showActivityIndicator() {
activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicatorView.center = center
activityIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
activityIndicatorView.startAnimating()
addSubview(activityIndicatorView)
}
func hideActivityIndicator() {
activityIndicatorView.removeFromSuperview()
}
}