iOS
Objective-C의 런타임
수색…
연결된 객체 사용
연관된 객체는 상태를 유지해야하는 기존 클래스에 기능을 추가하려는 경우에 유용합니다.
예를 들어, 모든 UIView에 활동 표시기 추가 :
목표 -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 런타임에 액세스 할 수도 있습니다.
신속한 코드
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()
}
}
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow