美文网首页
iOS 开发中一些技巧归纳

iOS 开发中一些技巧归纳

作者: 男儿心 | 来源:发表于2016-08-12 15:13 被阅读114次

    通过自己开发以及借鉴的别人的经验,总结一下一些开发中经常用到的技巧知识点,也算是做个小笔记吧。

    1、控件的局部圆角问题

    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的控件都可以

    //指定了需要成为圆角的角。该参数是UIRectCorner类型的,可选的值有:

    * UIRectCornerTopLeft

    * UIRectCornerTopRight

    * UIRectCornerBottomLeft

    * UIRectCornerBottomRight

    * UIRectCornerAllCorners

    从名字很容易看出来代表的意思,使用“|”来组合就好了。

    设置滑动的时候隐藏navigationBar2、navigationBar的透明问题

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

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

    [self.navigationController.navigationBar setBackgroundImage:[UIImage new]

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

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

    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:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:UIColorWithHexRGB(0xfe6d27)}];

    [[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:10],NSForegroundColorAttributeName : UIColorWithHexRGB(0x666666)} forState:UIControlStateNormal];

    [[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSiz]]

    4、navigationBar隐藏显示的过度

    一个页面隐藏navigationBar,另一个不隐藏。两个页面进行push和pop的时候,尤其是有侧滑手势返回的时候,不做处理就会造成滑动返回时,navigationBar位置是空的,直接显示一个黑色或者显示下面一层视图,很难看。这就需要我们加入过度动画来隐藏或显示navigationBar:

    在返回后将要出现的页面实现viewWillAppear方法,需要隐藏就设为YES,需要显示就设为NO

    - (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];

    [self.navigationController setNavigationBarHidden:NO animated:YES];

    }

    5、给webView添加头视图

    webView是一个复合视图,里面包含有一个scrollView,scrollView里面是一个UIWebBrowserView(负责显示WebView的内容)

    UIView *webBrowserView = self.webView.scrollView.subviews[0];//拿到webView的webBrowserView

    self.backHeadImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth*2/3.0)];

    [_backHeadImageView sd_setImageWithURL:[NSURL URLWithString:self.imageUrl] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];

    [self.webView insertSubview:_backHeadImageView belowSubview:self.webView.scrollView];

    //把backHeadImageView插入到webView的scrollView下面

    CGRect frame = self.webBrowserView.frame;

    frame.origin.y = CGRectGetMaxY(_backHeadImageView.frame);

    self.webBrowserView.frame = frame;

    //更改webBrowserView的frame向下移backHeadImageView的高度,使其可见

    6、模态跳转的动画设置

    设置模态跳转的动画,系统提供了四种可供选择

    DetailViewController *detailVC = [[DetailViewController alloc]init];

    //UIModalTransitionStyleFlipHorizontal 翻转

    //UIModalTransitionStyleCoverVertical 底部滑出

    //UIModalTransitionStyleCrossDissolve 渐显

    //UIModalTransitionStylePartialCurl 翻页

    detailVC.modalTransitionStyle = UIModalTransitionStylePartialCurl;

    [self presentViewController:detailVC animated:YES completion:nil];

    7、图片处理只拿到图片的一部分

    UIImage *image = [UIImage imageNamed:filename];

    CGImageRef imageRef = image.CGImage;

    CGRect rect = CGRectMake(origin.x, origin.y ,size.width, size.height);

    //这里的宽高是相对于图片的真实大小

    //比如你的图片是400x400的那么(0,0,400,400)就是图片的全尺寸,想取哪一部分就设置相应坐标即可

    CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);

    UIImage *imageRect = [[UIImage alloc] initWithCGImage:imageRefRect];

    8、调用代码使APP进入后台,达到点击Home键的效果

    [[UIApplication sharedApplication] performSelector:@selector(suspend)];

    suspend的英文意思有:暂停; 悬; 挂; 延缓;

    9、获取UIWebView的高度

    - (void)webViewDidFinishLoad:(UIWebView *)webView  {

    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];

    CGRect frame = webView.frame;

    webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);

    }

    10、去掉UITableView多余的分割线

    tableView.tableFooterView = [UIView new];

    11、调整cell分割线的位置,两个方法一起用

    -(void)viewDidLayoutSubviews {

    if ([self.mytableview respondsToSelector:@selector(setSeparatorInset:)]) {

    [self.mytableview setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

    }

    if ([self.mytableview respondsToSelector:@selector(setLayoutMargins:)])  {

    [self.mytableview setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];

    }

    }

    #pragma mark - cell分割线

    - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

    {

    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){

    [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

    }

    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {

    [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];

    }

    }

    12、UISearchController和UISearchBar的Cancle按钮改title问题,简单粗暴

    - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{

    searchController.searchBar.showsCancelButton = YES;

    UIButton *canceLBtn = [searchController.searchBar valueForKey:@"cancelButton"];

    [canceLBtn setTitle:@"取消" forState:UIControlStateNormal];

    [canceLBtn setTitleColor:[UIColor colorWithRed:14.0/255.0 green:180.0/255.0 blue:0.0/255.0 alpha:1.00] forState:UIControlStateNormal];

    searchBar.showsCancelButton = YES;

    return YES;

    }

    13、UITableView收起键盘何必这么麻烦

    一个属性搞定,效果好(UIScrollView同样可以使用)

    以前是不是觉得[self.view endEditing:YES];很屌,这个下面的更屌。

    yourTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

    另外一个枚举为UIScrollViewKeyboardDismissModeInteractive,表示在键盘内部滑动,键盘逐渐下去。

    14、NSTimer

    1、NSTimer计算的时间并不精确

    2、NSTimer需要添加到runLoop运行才会执行,但是这个runLoop的线程必须是已经开启。

    3、NSTimer会对它的tagert进行retain,我们必须对其重复性的使用intvailte停止。target如果是self(指UIViewController),那么VC的retainCount+1,如果你不释放NSTimer,那么你的VC就不会dealloc了,内存泄漏了。

    15、用十六进制获取UIColor(类方法或者Category都可以,这里我用工具类方法)

    + (UIColor *)colorWithHexString:(NSString *)color

    {

    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters

    if ([cString length] < 6) {

    return [UIColor clearColor];

    }

    // strip 0X if it appears

    if ([cString hasPrefix:@"0X"])

    cString = [cString substringFromIndex:2];

    if ([cString hasPrefix:@"#"])

    cString = [cString substringFromIndex:1];

    if ([cString length] != 6)

    return [UIColor clearColor];

    // Separate into r, g, b substrings

    NSRange range;

    range.location = 0;

    range.length = 2;

    //r

    NSString *rString = [cString substringWithRange:range];

    //g

    range.location = 2;

    NSString *gString = [cString substringWithRange:range];

    //b

    range.location = 4;

    NSString *bString = [cString substringWithRange:range];

    // Scan values

    unsigned int r, g, b;

    [[NSScanner scannerWithString:rString] scanHexInt:&r];

    [[NSScanner scannerWithString:gString] scanHexInt:&g];

    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];

    }

    16、获取今天是星期几

    + (NSString *) getweekDayStringWithDate:(NSDate *) date

    {

    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // 指定日历的算法

    NSDateComponents *comps = [calendar components:NSWeekdayCalendarUnit fromDate:date];

    // 1 是周日,2是周一 3.以此类推

    NSNumber * weekNumber = @([comps weekday]);

    NSInteger weekInt = [weekNumber integerValue];

    NSString *weekDayString = @"(周一)";

    switch (weekInt) {

    case 1:

    {

    weekDayString = @"(周日)";

    }

    break;

    case 2:

    {

    weekDayString = @"(周一)";

    }

    break;

    case 3:

    {

    weekDayString = @"(周二)";

    }

    break;

    case 4:

    {

    weekDayString = @"(周三)";

    }

    break;

    case 5:

    {

    weekDayString = @"(周四)";

    }

    break;

    case 6:

    {

    weekDayString = @"(周五)";

    }

    break;

    case 7:

    {

    weekDayString = @"(周六)";

    }

    break;

    default:

    break;

    }

    return weekDayString;

    }

    17、设置滑动的时候隐藏navigationBar

    navigationController.hidesBarsOnSwipe = Yes;

    18、iOS画虚线

    记得先 QuartzCore框架的导入#importCGContextRef context =UIGraphicsGetCurrentContext();

    CGContextBeginPath(context);

    CGContextSetLineWidth(context, 2.0);

    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);

    CGFloat lengths[] = {10,10};

    CGContextSetLineDash(context, 0, lengths,2);

    CGContextMoveToPoint(context, 10.0, 20.0);

    CGContextAddLineToPoint(context, 310.0,20.0);

    CGContextStrokePath(context);

    CGContextClosePath(context);

    19、自动布局中多行UILabel,需要设置其preferredMaxLayoutWidth属性才能正常显示多行内容。另外如果出现显示不全文本,可以在计算的结果基础上+0.5。

    CGFloat h = [model.message boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - kGAP-kAvatar_Size - 2*kGAP, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height+0.5;

    20、禁止程序运行时自动锁屏

    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];

    21、KVC相关,支持操作符

    KVC同时还提供了很复杂的函数,主要有下面这些

    ①简单集合运算符

    简单集合运算符共有@avg, @count , @max , @min ,@sum5种,都表示啥不用我说了吧, 目前还不支持自定义

    @interface Book : NSObject

    @property (nonatomic,copy)  NSString* name;

    @property (nonatomic,assign)  CGFloat price;

    @end

    @implementation Book

    @end

    Book *book1 = [Book new];

    book1.name = @"The Great Gastby";

    book1.price = 22;

    Book *book2 = [Book new];

    book2.name = @"Time History";

    book2.price = 12;

    Book *book3 = [Book new];

    book3.name = @"Wrong Hole";

    book3.price = 111;

    Book *book4 = [Book new];

    book4.name = @"Wrong Hole";

    book4.price = 111;

    NSArray* arrBooks = @[book1,book2,book3,book4];

    NSNumber* sum = [arrBooks valueForKeyPath:@"@sum.price"];

    NSLog(@"sum:%f",sum.floatValue);

    NSNumber* avg = [arrBooks valueForKeyPath:@"@avg.price"];

    NSLog(@"avg:%f",avg.floatValue);

    NSNumber* count = [arrBooks valueForKeyPath:@"@count"];

    NSLog(@"count:%f",count.floatValue);

    NSNumber* min = [arrBooks valueForKeyPath:@"@min.price"];

    NSLog(@"min:%f",min.floatValue);

    NSNumber* max = [arrBooks valueForKeyPath:@"@max.price"];

    NSLog(@"max:%f",max.floatValue);

    打印结果

    2016-04-20 16:45:54.696 KVCDemo[1484:127089] sum:256.000000

    2016-04-20 16:45:54.697 KVCDemo[1484:127089] avg:64.000000

    2016-04-20 16:45:54.697 KVCDemo[1484:127089] count:4.000000

    2016-04-20 16:45:54.697 KVCDemo[1484:127089] min:12.000000

    NSArray 快速求总和 最大值 最小值 和 平均值

    NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];

    CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];

    CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];

    CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];

    CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];

    NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);

    22、强制让App直接退出(非闪退,非崩溃)

    - (void)exitApplication {

    AppDelegate *app = [UIApplication sharedApplication].delegate;

    UIWindow *window = app.window;

    [UIView animateWithDuration:1.0f animations:^{

    window.alpha = 0;

    } completion:^(BOOL finished) {

    exit(0);

    }];

    }

    23、Label行间距

    NSMutableAttributedString *attributedString =

    [[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];

    NSMutableParagraphStyle *paragraphStyle =  [[NSMutableParagraphStyle alloc] init];

    [paragraphStyle setLineSpacing:3];

    //调整行间距

    [attributedString addAttribute:NSParagraphStyleAttributeName

    value:paragraphStyle

    range:NSMakeRange(0, [self.contentLabel.text length])];

    self.contentLabel.attributedText = attributedString;

    24、MRC和ARC混编设置方式

    在XCode中targets的build phases选项下Compile Sources下选择 不需要arc编译的文件

    双击输入 -fno-objc-arc 即可

    MRC工程中也可以使用ARC的类,方法如下:

    在XCode中targets的build phases选项下Compile Sources下选择要使用arc编译的文件

    双击输入 -fobjc-arc 即可

    25、把tableview里cell的小对勾的颜色改成别的颜色

    tableView.tintColor = [UIColor redColor];

    26、解决同时按两个按钮进两个view的问题

    [button setExclusiveTouch:YES];

    27、修改textFieldplaceholder字体颜色和大小

    textField.placeholder = @"请输入用户名";

    [textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];

    [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

    28、禁止textField和textView的复制粘贴菜单

    -(BOOL)canPerformAction:(SEL)action withSender:(id)sender

    {

    if ([UIMenuController sharedMenuController]) {

    [UIMenuController sharedMenuController].menuVisible = NO;

    }

    return NO;

    }

    29、二级三级页面隐藏系统tabbar

    1、单个处理

    YourViewController *yourVC = [YourViewController new];

    yourVC.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:yourVC animated:YES];

    2.统一在基类里面处理

    新建一个类BaseNavigationController继承UINavigationController,然后重写 -(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated这个方法。所有的push事件都走此方法。

    @interface BaseNavigationController : UINavigationController

    @end

    -(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{

    [super pushViewController:viewController animated:animated];

    if (self.viewControllers.count>1) {

    viewController.hidesBottomBarWhenPushed = YES;

    }

    }

    30、取消系统的返回手势

    self.navigationController.interactivePopGestureRecognizer.enabled = NO;

    31、修改UIWebView中字体的大小,颜色

    1、UIWebView设置字体大小,颜色,字体:

    UIWebView无法通过自身的属性设置字体的一些属性,只能通过html代码进行设置

    在webView加载完毕后,在

    - (void)webViewDidFinishLoad:(UIWebView *)webView方法中加入js代码

    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '60%'";

    [_webView stringByEvaluatingJavaScriptFromString:str];

    或者加入以下代码

    NSString *jsString = [[NSString alloc] initWithFormat:@"document.body.style.fontSize=%f;document.body.style.color=%@",fontSize,fontColor];

    [webView stringByEvaluatingJavaScriptFromString:jsString];

    欢迎补充。。。

    相关文章

      网友评论

          本文标题:iOS 开发中一些技巧归纳

          本文链接:https://www.haomeiwen.com/subject/ivxesttx.html