10个非常实用的iOS小技巧

2020-01-18 21:44:57于海丽

在开发过程中我们总会遇到各种各样的小问题,有些小问题并不是十分容易解决。在此我就总结一下,我在开发中遇到的各种小问题,以及我的解决方法。比较普遍的我就不再提了,这里主要讲一些你可能不知道的(当然,也有可能你都知道,大神就不必往下看了)

1、控件的局部圆角问题

你是不是也遇到过这样的问题,一个button或者label,只要右边的两个角圆角,或者只要一个圆角。该怎么办呢。这就需要图层蒙版来帮助我们了


CGRect rect = CGRectMake(0, 0, 100, 50); 
  CGSize radio = CGSizeMake(5, 5);//圆角尺寸 
  UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight;//这只圆角位置 
  UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio]; 
  CAShapeLayer *masklayer = [[CAShapeLayer alloc]init];//创建shapelayer 
  masklayer.frame = button.bounds; 
  masklayer.path = path.CGPath;//设置路径 
  button.layer.mask = masklayer; 

举例为button,其它继承自UIView的控件都可以

2、navigationBar的透明问题

如果仅仅把navigationBar的alpha设为0的话,那就相当于把navigationBar给隐藏了,大家都知道,父视图的alpha设置为0的话,那么子视图全都会透明的。那么相应的navigationBar的标题和左右两个按钮都会消失。这样显然达不到我们要求的效果。

(1)如果仅仅是想要navigationBar透明,按钮和标题都在可以使用以下方法:


[self.navigationController.navigationBar setBackgroundImage:[UIImage new] 
forBarMetrics:UIBarMetricsDefault];

//给navigationBar设置一个空的背景图片即可实现透明,而且标题按钮都在

细心的你会发现上面有一条线如下图:

iOS,技巧

这就需要我们做进一步处理,把线去掉,如下方法即可:


self.navigationController.navigationBar.shadowImage = [UIImage new]; 
 //其实这个线也是image控制的。设为空即可 

(2)如果你想在透明的基础上实现根据下拉距离,由透明变得不透明的效果,那么上面那个就显得力不从心了,这就需要我们采用另外一种方法了


//navigationBar是一个复合视图,它是有许多个控件组成的,那么我们就可以从他的内部入手 
[[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = 0;

//这里可以根据scrollView的偏移量来设置alpha就实现了渐变透明的效果 

3、全局设置navigationBar标题的样式和barItem的标题样式


//UIColorWithHexRGB( )这个方法是自己定义的,这里只需要给个颜色就好了 
[[UINavigationBar appearance] setBarTintColor:UIColorWithHexRGB(0xfefefe)]; 
 
  [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:[UIFontboldSystemFontOfSize:18],NSForegroundColorAttributeName:UIColorWithHexRGB(0xfe6d27)}]; 
 
 
  [[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName : [UIFontboldSystemFontOfSize:10],NSForegroundColorAttributeName : UIColorWithHexRGB(0x666666)}forState:UIControlStateNormal]; 
 
 
 [[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSiz