我即将开始一个包含大量 UI 定制的大项目。例如,我需要一个看起来像这样的 UIView:
所以我写了一个 UIView 自定义类,但我真的不知道我的代码是否经过优化以及是否有最好的方法来做到这一点,所以你能给我一些建议吗?
这是我的代码:
// DPIViewHeader.h
#define HEADER_HEIGHT 30.0f
#define HEADER_COLOR [UIColor colorWithRed:161.0f/255.0f green:209.0f/255.0f blue:249.0f/255.0f alpha:1.0f]
#define BORDER_WIDTH 2.0f
#define BORDER_COLOR [[UIColor colorWithRed:82.0f/255.0f green:159.0f/255.0f blue:210.0f/255.0f alpha:1.0f] CGColor]
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
@interface DPIViewWithHeaderTest : UIView
// properties
@property (strong, nonatomic) NSString *title;
@property (strong, nonatomic) UIColor *headerColor;
@property (strong, nonatomic) UIView *headerView;
@property (strong, nonatomic) UIView *contentView;
// methods
- (id)initWithFrame:(CGRect)frame title:(NSString *)title;
- (id)initWithFrame:(CGRect)frame title:(NSString *)title headerColor:(UIColor *)headerColor;
@end
// DPIViewHeader.m
#import "DPIViewWithHeaderTest.h"
@implementation DPIViewWithHeaderTest
- (id)initWithFrame:(CGRect)frame title:(NSString *)title {
self = [super initWithFrame:frame];
if (self) {
self.title = title;
}
return self;
}
- (void)layoutSubviews {
// set header view and content view
self.headerView = [[UIView alloc] initWithFrame:CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.frame.size.width, HEADER_HEIGHT)];
self.contentView = [[UIView alloc] initWithFrame:CGRectMake(self.bounds.origin.x, self.bounds.origin.y + HEADER_HEIGHT, self.frame.size.width, self.frame.size.height - HEADER_HEIGHT)];
// add title label
UILabel *label = [[UILabel alloc] init];
label.text = self.title;
[label sizeToFit];
label.center = CGPointMake(label.frame.size.width/2 + 10, self.headerView.frame.size.height/2);
label.backgroundColor = [UIColor clearColor];
[self.headerView addSubview:label];
// set color header
self.headerView.backgroundColor = HEADER_COLOR;
// set border attributes
self.layer.borderWidth = BORDER_WIDTH;
self.layer.borderColor = BORDER_COLOR;
self.headerView.layer.borderWidth = BORDER_WIDTH;
self.headerView.layer.borderColor = BORDER_COLOR;
// add subviews
[self addSubview:self.headerView];
[self addSubview:self.contentView];
}
@end