使用UIView抽象出常见的UI(很像网页中的“部分”)drawRect vs init vs layoutSubviews

时间:2014-10-16 14:46:13

标签: ios objective-c uiview

我试图通过将常用UI抽象为UIView子类并在我的VC中实例化它们来使我的View Controllers更精简,就像我在web dev中创建HTML模板一样。

这是我的VC:

- (void)addEmptyView {
    self.emptyHomeView = [[PLOTEmptyHomeView alloc] initWithFrame:CGRectMake(0, 10, self.view.bounds.size.width, self.view.bounds.size.height - 113) andUser:self.userModel.user];
    [self.view addSubview:self.emptyHomeView];
}

UIView I子类化并实例化:

- (id)initWithFrame:(CGRect)frame andUser:(NSDictionary *)user {
    self = [super initWithFrame:frame];
    if(self){
        self.user = user;
        [self drawUI];
    }
    return self;
}

- (void)drawUI {
    self.arrowUp = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow-up"]];
    CGRect arrowUpFrame = self.arrowUp.frame;
    arrowUpFrame.origin.x = self.bounds.size.width - 60;
    arrowUpFrame.size.width = 33.75;
    arrowUpFrame.size.height = 33;
    self.arrowUp.frame = arrowUpFrame;
    [self addSubview:self.arrowUp];

    self.welcome = [[UILabel alloc] initWithFrame:CGRectMake(0, 167.5, self.bounds.size.width, 22.5)];
    NSArray *nameParts = [self.user[@"name"] componentsSeparatedByString:@" "];
    self.welcome.text = [NSString stringWithFormat:@"Hey %@", nameParts[0]];
    self.welcome.font = [UIFont fontWithName:@"Avenir-Light" size:24];
    self.welcome.textColor = [UIColor plotPlaceholderGrey];
    self.welcome.textAlignment = NSTextAlignmentCenter;
    [self addSubview:self.welcome];
}

现在这段代码一切正常,但是出于我自己的理解,我是否滥用了init方法?我也知道layoutSubviews& drawRect中的UIView,但我不确定我是否应该在上述情况中使用它们?

任何指针都表示赞赏......

2 个答案:

答案 0 :(得分:0)

最理想的是,您可以在方法中实例化和添加子视图,如图所示,但是实际布局涉及layoutSubviews中的框架。您拥有的代码将按原样运行,但如果您的初始化是来自笔尖或者没有提供核心框架(或涉及自动布局)的东西,那么您可能无法在初始化时真正知道正确的边界/框架。布局代码通常取决于可能发生变化的其他因素,因此layoutSubviews是一个更合适的位置。

答案 1 :(得分:0)

您没有滥用init方法,但您必须声明所有ui对象及其所有属性而不定义框架,并且在layoutsubviews中,您定义所有对象的框架。这是我申报自定义视图的方式。

- (id)initWithFrame:(CGRect)frame andUser:(NSDictionary *)user {
    self = [super initWithFrame:frame];
    if(self){
      self.user = user;
      self.arrowUp = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow-up"]];
     [self addSubview:self.arrowUp];
     self.welcome = [[UILabel alloc] init];


   NSArray *nameParts = [self.user[@"name"] componentsSeparatedByString:@" "];
    self.welcome.text = [NSString stringWithFormat:@"Hey %@", nameParts[0]];
  self.welcome.font = [UIFont fontWithName:@"Avenir-Light" size:24];
  self.welcome.textColor = [UIColor plotPlaceholderGrey];
  self.welcome.textAlignment = NSTextAlignmentCenter;
  [self addSubview:self.welcome];

   }
   return self;
}

- (void)layoutSubviews {
   CGRect arrowUpFrame = self.arrowUp.frame;
   arrowUpFrame.origin.x = self.bounds.size.width - 60;
   arrowUpFrame.size.width = 33.75;
   arrowUpFrame.size.height = 33;
   self.arrowUp.frame = arrowUpFrame;

  self.welcome.frame =CGRectMake(0, 167.5, self.bounds.size.width, 22.5)];
}

希望它会对你有所帮助。