尽管iOS原生的UI控件就已经有很不错的显示效果,但是App开发者仍然希望自己的产品与众不同,所以自定义UI外观成了每个App产品开发必做之事。今天就来做一个在iOS6下实现自定义UI的demo,内容及Demo来源于国外iOS博客raywenderlich,先看看美化前后效果差别(左边为美化前,右边为美化后):
整个Demo里面几乎包含所有iOS下的UI控件,以下我只对关键代码给出说明,详情大家可以下载附上的Demo源码查看。好了,首先在AppDelegate.m中新建了一个方法customizeApperance(),所有的美化效果都在这个方法里完成,并且在application:didFinishLauchingWithOptions:里面调用这个方法。
1.自定义导航栏
//竖屏 UIImage *image44 = [[UIImage imageNamed:@"surf_gradient_textured_44"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)]; [[UINavigationBar appearance] setBackgroundImage:image44 forBarMetrics:UIBarMetricsDefault]; //横屏 UIImage *gradientImage32 = [[UIImage imageNamed:@"surf_gradient_textured_32"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)]; [[UINavigationBar appearance] setBackgroundImage:gradientImage32 forBarMetrics:UIBarMetricsLandscapePhone];
图片只会被拉伸红色矩形区域,假如红框左右距离图片边距分别为25,距离上下边距为0,则Insets的写法就是这样:UIEdgetInsetsMake(0,25,0,25),如果要使整张图片拉伸,则四个参数全部传0即可。代码中分别指定了横屏和竖屏下的两种方式。
同时,可以指定导航栏底部的阴影图片、颜色和UIBarButtonItem的样式等:
[[UINavigationBar appearance] setShadowImage:[UIImage imageNamed:@"navBarShadow"]];
UIImage *button30 = [[UIImage imageNamed:@"button_textured_30"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 5, 0, 5)]; [[UIBarButtonItem appearance] setBackgroundImage:button30 forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
UIImage *buttonBack30 = [[UIImage imageNamed:@"button_back_textured_30"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 13, 0, 5)]; [[UIBarButtonItem appearance] setBackButtonBackgroundImage:buttonBack30 forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
2.设置底部Tab栏的样式(背景、选中、默认)
UIImage *tabBackground = [[UIImage imageNamed:@"tab_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)]; [[UITabBar appearance] setBackgroundImage:tabBackground]; [[UITabBar appearance] setSelectionIndicatorImage: [UIImage imageNamed:@"tab_select_indicator"]];效果如下:
3.自定义UISwitch
//指定开关两种状态下背景颜色和滑动杆颜色 [[UISwitch appearance] setOnTintColor:[UIColor colorWithRed:0 green:175.0/255.0 blue:176.0/255.0 alpha:1.0]]; [[UISwitch appearance] setTintColor:[UIColor colorWithRed:1.000 green:0.989 blue:0.753 alpha:1.000]]; [[UISwitch appearance] setThumbTintColor:[UIColor yellowColor]]; //指定开关两种状态下背景图片(YES、NO) [[UISwitch appearance] setOnImage:[UIImage imageNamed:@"yesSwitch"]]; [[UISwitch appearance] setOffImage:[UIImage imageNamed:@"noSwitch"]];效果如下:
4.自定义UIPageControl
//选中状态颜色 [[UIPageControl appearance] setCurrentPageIndicatorTintColor:[UIColor colorWithRed:0 green:175.0/255.0 blue:176.0/255.0 alpha:1.0]]; //未选中状态颜色 [[UIPageControl appearance] setPageIndicatorTintColor:[UIColor colorWithRed:0.996 green:0.788 blue:0.180 alpha:1.000]];
这里简要说明了几种控件的自定义效果,查看其他控件自定义效果,大家可以下载Demo仔细查看并根据自己的需要进行定制
Demo源码下载:代码
加入我们的或微信公众账号请查看:Ryan's zone公众账号及
同时欢迎关注我的新浪微博和我交流:@唐韧_Ryan