OGeek|极客世界-中国程序员成长平台

标题: ios - 类别最佳做法 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 21:11
标题: ios - 类别最佳做法

我正在使用 categories 来处理一些我以前可能使用继承的事情。

我现在正在做的事情更像是一个最佳实践问题,我不确定它应该如何实现。我正在写一个关于 UIActivityIndi​​catorView 的类别,它基本上将用于将事件指示器放在任意 View 中。下面你会找到我如何做的代码示例,我的主要问题是这是否好。如果是这样的话,我会很感激评论为什么它很糟糕。谢谢。

类别:

@interface UIActivityIndicatorView (Customizations)
    - (UIActivityIndicatorView *) inViewUIView *) target;
@end

实现:

@implementation UIActivityIndicatorView (Customizations)

- (UIActivityIndicatorView *) inViewUIView *) target {
    [self startAnimating];
    [self setHidden:NO];
    self.frame = target.bounds;
    self.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.6f];

    return self;
}
@end

那我会这样使用:

[background addSubview:[loader inView:background]];

我猜另一种方法是创建一个初始化函数来获取容器 View 并仅返回“样式化” View ,或者可能不返回任何内容(void)而只是让方法做样式。

所以我正在寻找一些关于如何处理这个问题的指导。



Best Answer-推荐答案


What kind of worries me is that I am actually making a second copy of the UIActivityIndicatorView which seem unnecessary

不,你没有。您可能会对您从类别方法返回 self 的事实感到困惑,但这只是一个指针,而不是被复制的对象本身。

但是,我的实现方式会略有不同:

- (void) addToSuperViewUIView *) target {
    [self startAnimating];
    [self setHidden:NO];
    self.frame = target.bounds;
    self.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.6f];

    [target addSubview:self];
}

这样,您在添加时不需要进行额外的、不必要的调用:

[loader addToSuperView:background];

关于ios - 类别最佳做法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10754167/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4