iOS开发中一些小功能

1.给UITableViewCell添加滚动动画

<small>主要实现tableview的下面代理方法,设置cell的transform属性</small>

#define ScreenW [UIScreen mainScreen].bounds.size.width

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    cell.transform = CGAffineTransformTranslate(cell.transform, ScreenW/2, 0);
    [tableView bringSubviewToFront:cell];
    [UIView animateWithDuration:.5f
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         cell.transform = CGAffineTransformIdentity;
                     } completion:nil];
}

2.给视图添加视觉偏移效果

<small>主要实现类似手机桌面偏移效果

        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
        view.backgroundColor = [UIColor grayColor];
        [self addSubview:view];

        UIInterpolatingMotionEffect *motionEffect;
        motionEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
        motionEffect.minimumRelativeValue = @(-25);
        motionEffect.maximumRelativeValue = @(25);
        [view addMotionEffect:motionEffect];
        motionEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
        motionEffect.minimumRelativeValue = @(-25);
        motionEffect.maximumRelativeValue = @(25);
        [view addMotionEffect:motionEffect];

3.后台运行进行数据的保存

<small>如果你的应用在home键退出到后台时希望保存数据或进行一些处理,那么为了延长应用在后台的运行时间你可以用UIApplication 的 beginBackgroundTaskWithExpirationHandler 方法,让应用最多有 10 分钟的时间在后台运行。具体使用方法:

//AppDelegate.h
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;

//AppDelegate.m
- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    [self beginBackgroundUpdateTask];
    //添加需要后台长久运行的代码
    //TODO...
    [self endBackgroundUpdateTask];
    
}

- (void)beginBackgroundUpdateTask{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void)endBackgroundUpdateTask{
    [[UIApplication sharedApplication] endBackgroundTask:self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

4.设备播放短音频和震动

<small>具体使用方法:

// 播放声音
- (SystemSoundID)playSound
{
    // 要播放的音频文件地址
    NSURL *bundlePath = [[NSBundle mainBundle] URLForResource:@"MyTest" withExtension:@"bundle"];
    NSURL *audioPath = [[NSBundle bundleWithURL:bundlePath] URLForResource:@"in" withExtension:@"caf"];
    // 创建系统声音,同时返回一个ID
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(audioPath), &soundID);
    // Register the sound completion callback.
    AudioServicesAddSystemSoundCompletion(soundID,
                                          NULL, // uses the main run loop
                                          NULL, // uses kCFRunLoopDefaultMode
                                          EMSystemSoundFinishedPlayingCallback, // the name of our custom callback function
                                          NULL // for user data, but we don't need to do that in this case, so we just pass NULL
                                          );
    
    AudioServicesPlaySystemSound(soundID);
    
    return soundID;
}

// 震动
- (void)playVibration
{
    // Register the sound completion callback.
    AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate,
                                          NULL, // uses the main run loop
                                          NULL, // uses kCFRunLoopDefaultMode
                                          EMSystemSoundFinishedPlayingCallback, // the name of our custom callback function
                                          NULL // for user data, but we don't need to do that in this case, so we just pass NULL
                                          );
    
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

5.

//tableView cell 中的输入框被键盘挡住 最快捷方法

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

        UITableViewController *tvc = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
        [self addChildViewController:tvc];
        _tableView = tvc.tableView;
        //添加以上3行代码 即可
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = [UIColor yqwLineColor];
        _tableView.backgroundColor = [UIColor yqwBackgroundColor];
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[QMProduceAmountInfoCell class] forCellReuseIdentifier:kInfoCellIdentifier];
        [_tableView registerClass:[QMPayMethodCell class] forCellReuseIdentifier:kPayCellIdentifier];
    }
    return _tableView;
}

6.自定义抛出异常

- (instancetype)init
{
    //方法一
    @throw [NSException exceptionWithName:@"init error" reason:@"please use shareInstance instead of init" userInfo:nil];
    //方法二
    NSException *except = [NSException exceptionWithName:@"init error" reason:@"please use shareInstance instead of init" userInfo:nil];
    [except raise];
    return [super init];
}

7.实时修改状态栏颜色

//1.在需要改变的地方调用,比如
#pragma mark - ScrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    _offsetY = scrollView.contentOffset.y;
    [self setNeedsStatusBarAppearanceUpdate];   
}
//2.UIViewController实现下面方法
#pragma mark - preferredStatusBarStyle
- (UIStatusBarStyle)preferredStatusBarStyle {
    if(_offsetY>kNavigation_Bar_Height){
        return UIStatusBarStyleDefault;
    }
    return UIStatusBarStyleLightContent;
}

8.tableView reloadSections抖动的问题

解决
方法 一:[UIView performWithoutAnimation:^{
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        }];
方法 二:self.tableView.estimatedRowHeight = 0;

9.textView 添加链接并改变链接颜色

NSString *text = @"我同意";
NSString *rule = @"《用户注册协议》";
NSString *totalStr = [NSString stringWithFormat:@"%@%@",text,rule];
    _attrStr = [[NSMutableAttributedString alloc] initWithString:totalStr];
//这样添加无效
//    [_attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.redColor range:NSMakeRange(text.length, rule.length)];
    [_attrStr addAttributes:@{NSLinkAttributeName:[NSURL URLWithString:@""]} range:NSMakeRange(text.length, rule.length)];
    _textView.attributedText = _attrStr;
//指定链接颜色
    _textView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor redColor]};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 自从古老的iOS4以来,当用户点击home建的时候,你可以使你的APP们在内存中处于suspended(挂起)状态...
    木易林1阅读 3,220评论 1 4
  • *7月8日上午 N:Block :跟一个函数块差不多,会对里面所有的内容的引用计数+1,想要解决就用__block...
    炙冰阅读 2,553评论 1 14
  • 1.属性readwrite,readonly,assign,retain,copy,nonatomic 各是什么作...
    曾令伟阅读 1,081评论 0 10
  • 会不会也有人跟我一样,自己一个人的时候,插上耳机,会不自觉的想很多的事,开心的,悲伤的,对以往的种种不停的回忆着,...
    大懒丫阅读 292评论 0 1