XIB
1.继承UIView创建View类,命名ViewA
2.新建一个Xib,取名ViewA
#import <UIKit/UIKit.h>
@interface ViewA : UIView
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
- (void)configeWithImage:(UIImage *)image;
@end
#import "ViewA.h"
@implementation ViewA
- (void)awakeFromNib {
[super awakeFromNib];
_imageView.layer.masksToBounds = YES;
_imageView.layer.cornerRadius = self.frame.size.width/2;
}
- (void)configeWithImage:(UIImage *)image {
_imageView.image = image;
}
-(void)layoutSubviews {
[super layoutSubviews];
_imageView.layer.cornerRadius = self.frame.size.width/2;
}
@end
3.使用ViewA
ViewA * viewA = [[[NSBundle mainBundle] loadNibNamed:@"ViewA" owner:nil options:nil] lastObject];
viewA.frame = CGRectMake(0, 0, 100, 100);
[viewA configeWithImage:[UIImage imageNamed:@"123"]];
[self.view addSubview:viewA];
纯代码
#import <UIKit/UIKit.h>
@interface ViewB : UIView
@property (nonatomic , strong) UIImageView * imageView;
- (void)configeWithImage:(UIImage *)image;
@end
#import "ViewB.h"
@implementation ViewB
-(instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
_imageView.contentMode = UIViewContentModeScaleAspectFill;
_imageView.layer.masksToBounds = YES;
_imageView.layer.cornerRadius = frame.size.width/2;
[self addSubview:_imageView];
}
return self;
}
//如果需要对子视图重新布局,需要调用layoutSubViews方法:
-(void)layoutSubviews {
[super layoutSubviews];
_imageView.frame = self.frame;
_imageView.layer.cornerRadius = self.frame.size.width/2;
}
- (void)configeWithImage:(UIImage *)image {
_imageView.image = image;
}
@end
使用ViewB
ViewB * viewB = [[ViewB alloc] initWithFrame:CGRectMake(0, 80, 150, 150)];
[viewB configeWithImage:[UIImage imageNamed:@"123"]];
[self.view addSubview:viewB];
网友评论