我对 UIView 进行了子类化,因此可以将多个相同类型的视图添加到我的项目中。视图基本上是一个有半径的矩形,左边是一张图片,右边是一段文字。现在不要误会我的意思,下面的代码是有效的,但我总是问自己“是这样吗,还是我真的弄错了”。
1)我正在将 CALayers 与 UILabels 混合,可以吗?
2) setUpView 是按照它的方式完成的。
3)如果没问题,让 imageLayer 响应触摸事件的最佳选择是什么?
4)我也可以问一个附带问题吗?作为一个在商店里只有一个基本应用程序的兼职初学者,我有点挑剔。我的意思是,我是否应该让它工作并继续努力!你怎么看?
@synthesize dateLabel = _dateLabel;
@synthesize nameLabel = _nameLabel;
@synthesize photo = _photo;
@synthesize roundRect= _roundRect;
@synthesize imageLayer = _imageLayer;
-(void)setUpView
{
//create the white rectangle
self.roundRect.frame = CGRectMake(0.0, 0.0, self.frame.size.width, self.frame.size.height);
self.roundRect.cornerRadius = 15.0;
self.roundRect.backgroundColor = [UIColor clearColor].CGColor;
self.roundRect.borderColor = [UIColor whiteColor].CGColor;
self.roundRect.borderWidth = 2.0;
self.roundRect.masksToBounds = YES;
//create the photo
CGImageRef image = [self.photo CGImage];
self.imageLayer.frame = CGRectMake(0.0, 0.0, self.roundRect.frame.size.width*0.48, self.roundRect.frame.size.height);
self.imageLayer.borderColor = [UIColor whiteColor].CGColor;
self.imageLayer.borderWidth = 2.0;
self.imageLayer.masksToBounds = YES;
[self.imageLayer setContents:(__bridge id)image];
[self.imageLayer setContentsGravity:kCAGravityResizeAspectFill];
[self.imageLayer setContentsRect:CGRectMake(0.0,0.0,1.1,1.0)];
//create label
self.nameLabel.frame = CGRectMake(self.imageLayer.frame.size.width+5, self.roundRect.frame.size.height*0.05, self.roundRect.frame.size.width*0.48,self.roundRect.frame.size.height*0.35);
self.nameLabel.backgroundColor = [UIColor clearColor];
self.nameLabel.textAlignment = UITextAlignmentCenter;
self.nameLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
self.nameLabel.textColor = [UIColor whiteColor];
self.nameLabel.adjustsFontSizeToFitWidth =YES;
self.nameLabel.font = [UIFont fontWithName:@"Gill Sans" size:50.0];
[self.roundRect addSublayer:self.imageLayer];
[self.layer addSublayer:self.roundRect];
[self addSubview:self.nameLabel];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
}
-(void)setPhoto:(UIImage *)photo
{
_photo = photo;
[self setUpView];
}
-(void)setNameLabel:(UILabel *)nameLabel
{
_nameLabel = nameLabel;
[self setUpView];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.roundRect = [[CALayer alloc]init];
self.imageLayer = [[CALayer alloc]init];
self.nameLabel = [[UILabel alloc]init];
[self setUpView];
}
return self;
}