在开发中,如果是编码来实例化相关UI,则会经常重复书写同样的代码,以致造成代码冗余。
其实,我们可以根据需要自定义相关的实例化方法,并设置好相关的参数,即可简化实例化方法。
详细实践方法如下(以UIView为例):
步骤1:自定义简化实例化方法
/// 实例化UIView
UIView *InsertView(id view, CGRect rect, UIColor *backColor);
/// 实例化UIView,带边框
UIView *InsertViewWithBorder(id view, CGRect rect, UIColor *backColor, CGFloat borderwidth, UIColor *bordercolor);
/// 实例化UIView,带边框和圆角
UIView *InsertViewWithBorderAndCorRadius(id view, CGRect rect, UIColor *backColor, CGFloat borderwidth, UIColor *bordercolor, CGFloat corRadius);
步骤2:实现自定义实例化的方法
UIView *InsertView(id view, CGRect rect, UIColor *backColor)
{
return InsertViewWithBorder(view, rect, backColor, 0.0, nil);
}
UIView *InsertViewWithBorder(id view, CGRect rect, UIColor *backColor, CGFloat borderwidth, UIColor *bordercolor)
{
return InsertViewWithBorderAndCorRadius(view, rect, backColor, borderwidth, bordercolor, 0.0);
}
UIView *InsertViewWithBorderAndCorRadius(id view, CGRect rect, UIColor *backColor, CGFloat borderwidth, UIColor *bordercolor, CGFloat corRadius)
{
UIView *_view = [[UIView alloc] initWithFrame:rect];
_view.backgroundColor = backColor;
if (view)
{
[view addSubview:_view];
}
if (bordercolor && 0.0 != borderwidth)
{
_view.layer.borderWidth = borderwidth;
_view.layer.borderColor = bordercolor.CGColor;
}
if (0.0 != corRadius)
{
_view.layer.cornerRadius = corRadius;
}
return [_view autorelease];
}
步骤3:使用(见效果图)
// 创建view
InsertView(self.window, CGRectMake(10.0, 60.0, 60.0, 60.0), [UIColor orangeColor]);
// 创建带边框的view
InsertViewWithBorder(self.window, CGRectMake(30.0, 130.0, 60.0, 60.0), [UIColor greenColor], 0.5, [UIColor purpleColor]);
// 创建带边框及圆角的view
InsertViewWithBorderAndCorRadius(self.window, CGRectMake(60.0, 200.0, 60.0, 60.0), [UIColor brownColor], 1.2, [UIColor redColor], 10.0);