iOS学习笔记——第五天

iOS学习笔记——第五天

昨日回顾

昨天的购物车实例简单地体现mvc设计模式,让我们回顾下view的封装。
iOS学习笔记——第五天

  • 如果一个view内部的子控件比较多,一般会考虑自定义一个view,把它内部子控件的创建屏蔽起来,不让外界关心。
  • 外界可以传入对应的模型数据给view,view拿到模型数据后给内部的子控件设置对应的数据。
封装控件的基本步骤
  • 在initWithFrame: 方法中添加子控件,提供便利构造方法。
  • 在layoutSubview方法中设置子控件的frame(一定要调用super的layoutSubviews)。
  • 增加模型属性,在模型属性set方法中设置数据到子控件上。

今日学习概述

今日主要学习通过xib自定义控件和UIButton调整内部子控件位置。

通过xib自定义控件

  1. 创建xib文件,拖好对应控件。

  2. 创建一个继承UIView的类,与xib文件进行关联。iOS学习笔记——第五天

  3. 将控件属性作为私有成员拖入到"NBAView.m"的类扩展中,在"NBAView.h"中提供set方法并在"NBAView.m"实现set方法。"NBAView.m"代码如下。

#import "NBAView.h"
@interface NBAView ()

@property (weak, nonatomic) IBOutlet UIImageView *nbaImageView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *subtitleLabel;
@property (weak, nonatomic) IBOutlet UIButton *followButton;

@end

@implementation NBAView

- (void) setIcon:(NSString *)icon
{
    [self.nbaImageView setImage:[UIImage imageNamed:icon]];
}
- (void) setTitle:(NSString *)title
{
    [self.titleLabel setText:title];
}
- (void) setSubtitle:(NSString *)subtitle
{
    [self.subtitleLabel setText:subtitle];
}
- (void) setFollow:(NSString *)follow
{
    [self.followButton setTitle:follow forState:UIControlStateNormal];
}

@end
  1. 在控制器中注入数据。
  _nbaView = [[[NSBundle mainBundle] loadNibNamed:@"NBAxib" owner:nil options:nil] firstObject];
    _nbaView.frame = CGRectMake(0, 100, 375, 114);
    [_nbaView setIcon:@"1"];
    [_nbaView setTitle:@"库里获得2016-17赛季总冠军"];
    [_nbaView setSubtitle:@"库里获得2016-17赛季总冠军"];
    [_nbaView setFollow:@"333跟帖"];
    
    [self.view addSubview:_nbaView];

这样基本实现了view和controller的分离。以下是效果图。
iOS学习笔记——第五天

  • xib使用注意事项
    1> 如果一个view从xib中加载,就不能用init和initWithFrame:创建。
    2> 如果一个xib经常被使用,应该提供快速构造方法。
    3> 如果一个view从xib中加载:用代码添加一些子控件,得在initWithCoder:和awakeFromNib创建。
    4> 如果一个view从xib中加载,会调用initWithCoder:和awakeFormNib,不会调用init和initWithFrame:方法。

UIButton调整内部子控件位置

方式一:可以通过继承UIButton并重写其- (CGRect)titleRectForContentRect:(CGRect)contentRect和- (CGRect)imageRectForContentRect:(CGRect)contentRect方法。

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]){
        //文本居中
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        //改变图片的内容模式
        self.imageView.contentMode = UIViewContentModeCenter;
    }
    return self;
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    return CGRectMake(0, 0, 100, 60);
}
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    return CGRectMake(100, 0, 50, 60);
}

方式二:可以通过继承UIButton并重写其- (void)layoutSubviews方法。

- (void)layoutSubviews{
    [super layoutSubviews];
    self.imageView.frame = CGRectMake(100, 0, 50, 60);
    self.titleLabel.frame = CGRectMake(0, 0, 100, 60);
}