这是创建自定义UIView的方式吗?
问题描述:
我已经将子类UIView,所以我可以添加多个相同类型的视图到我的项目。该视图基本上是一个带半径的矩形,左侧是一张图片,右侧是一段文字。现在,请不要误解我的代码以及所有的代码,但是我总是问自己:“是这样的,还是我弄错了”。这是创建自定义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;
}
答
您可以通过使用Interface Builder来简化操作。我会创建一个UIView设置为我想要的大小的XIB。然后添加一个标签(nameLabel)并将其配置为您喜欢的方式。您可以使用QuartzCore图层cornerRadius来设置圆角。然后,您可以在XIB中使用您的子类,并将其设置为UIView的类类型。不是文件所有者,而是视图。然后你可以将你的标签作为出口连接,你不需要手动创建它。你可以删除上面的一些代码,仍然有你的功能和外观。我已经学会了让界面生成器尽可能地完成工作。
希望这会有所帮助。
伟大的东西,欢呼的队友。我会给它一个去! – 2012-04-27 21:07:06