iOS 常用知识总结

  • 1.隐藏导航栏上的返回字体
//Swift
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics: .Default)
//OC
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
  • 2.去掉tableView多余的线条
//Swift
self.tableView?.tableFooterView = UIView()
//OC
self.tableView.tableFooterView = [UIView new];
  • 3.去掉tableView的线条
//Swift
self.tableView?.separatorStyle = .None
//OC
 self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  • 4.去掉cell的选中效果
//Swift
cell.selectionStyle = .None
//OC
cell.selectionStyle = UITableViewCellSelectionStyleNone;
  • 5.解决tableview的分割线短一截
-(void)viewDidLayoutSubviews

{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }

    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
  • 6.在swift中定义协议的时候,如果使用如下方法定义,需要在声明时,使用weak来修饰以防止循环引用
@objc protocol BookTabBarDelegate{
    func commet()
    func commetnController()
    func likeBook()
    func shareAction()
}
weak var delegate:BookTabBarDelegate?
  • 7.如果使用swift语法声明一个协议时,不用使用weak进行修饰,否则会报错
protocol BookTabBarDelegate{
    func commet()
    func commetnController()
    func likeBook()
    func shareAction()
}
var delegate:BookTabBarDelegate?
  • 8.动态隐藏NavigationBar
//1.当我们的手离开屏幕时候隐藏
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    NSLog(@"======== %lf", velocity.y);
    if(velocity.y > 0) {
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }
    else {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
}
velocity.y这个量,在上滑和下滑时,变化极小(小数),但是因为方向不同,有正负之分,这就很好处理了。

效果图:

//2.在滑动过程中隐藏
//像safari
(1) self.navigationController.hidesBarsOnSwipe = YES;
(2)- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y + _familyTableView.contentInset.top;//注意
    CGFloat panTranslationY = [scrollView.panGestureRecognizer translationInView:self.familyTableView].y;

    if (offsetY > 64) {
        if (panTranslationY > 0) { //下滑趋势,显示
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }
        else {  //上滑趋势,隐藏
            [self.navigationController setNavigationBarHidden:YES animated:YES];
        }
    }
    else {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
}

这里的offsetY > 64只是为了在视图滑过navigationBar的高度之后才开始处理,防止影响展示效果。
panTranslationY是scrollView的pan手势的手指位置的y值,可能不是太好,因为panTranslationY这个值在较小幅度上下滑动时,可能都为正或都为负,这就使得这一方式不太灵敏.

效果图:

  • 9.设置导航栏透明
//方法一:设置透明度
  [[[self.navigationController.navigationBar subviews]objectAtIndex:0] setAlpha:0.1];
//方法二:设置背景图片
/**
 *  设置导航栏,使其透明
 *
*/
- (void)setNavigationBarColor:(UIColor *)color targetController:(UIViewController *)targetViewController
{

  //导航条的颜色 以及隐藏导航条的颜色
targetViewController.navigationController.navigationBar.shadowImage = [[UIImage alloc]init];
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [targetViewController.navigationController.navigationBar setBackgroundImage:theImage forBarMetrics:UIBarMetricsDefault];
}
  • 10.设置字体和行间距
//设置字体和行间距
    UILabel  * lable = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 300, 200)];
    lable.text = @"大家好,我是Frank_chun,在这里我们一起学习新的知识,总结我们遇到的那些坑,共同的学习,共同的进步,共同的努力,只为美好的明天!!!有问题一起相互的探讨--438637472!!!";
    lable.numberOfLines = 0;
    lable.font = [UIFont systemFontOfSize:12];
    lable.backgroundColor = [UIColor grayColor];
    [self.view addSubview:lable];

    //设置每个字体之间的间距
    //NSKernAttributeName 这个对象所对应的值是一个NSNumber对象(包含小数),作用是修改默认字体之间的距离调整,值为0的话表示字距调整是禁用的;
    NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:lable.text attributes:@{NSKernAttributeName:@(5.0)}];

    //设置某写字体的颜色
    //NSForegroundColorAttributeName 设置字体颜色
    NSRange blueRange = NSMakeRange([[str string] rangeOfString:@"Frank_chun"].location, [[str string] rangeOfString:@"Frank_chun"].length);
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange];

    NSRange blueRange1 = NSMakeRange([[str string] rangeOfString:@"438637472"].location, [[str string] rangeOfString:@"438637472"].length);
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange1];

    //设置每行之间的间距
    //NSParagraphStyleAttributeName 设置段落的样式
    NSMutableParagraphStyle * par = [[NSMutableParagraphStyle alloc]init];
    [par setLineSpacing:20];
    //为某一范围内文字添加某个属性
    //NSMakeRange表示所要的范围,从0到整个文本的长度
    [str addAttribute:NSParagraphStyleAttributeName value:par range:NSMakeRange(0, lable.text.length)];

    [lable setAttributedText:str];

效果图:

  • 11.点击button倒计时
//第一种方法
//点击button倒计时
#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) UIButton * timeButton;
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, strong)UIButton * btn;

@end

@implementation ViewController
{
    NSInteger _time;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    _time = 5;

    self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
    _btn.backgroundColor = [UIColor orangeColor];
    [_btn setTitle:@"获取验证码" forState:UIControlStateNormal];
    _btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [_timeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self refreshButtonWidth];
    [self.view addSubview:self.btn];
}
- (void)refreshButtonWidth
{
    CGFloat width = 0;
    if (_btn.enabled) {
        width = 100;
    }
    else {
        width = 200;
    }
    _btn.center = CGPointMake(self.view.frame.size.width/2, 200);
    _btn.bounds = CGRectMake(0, 0, width, 40);
    //每次刷新,保证区域正确
    [_btn setBackgroundImage:[self imageWithColor:[UIColor orangeColor] andSize:_btn.frame.size] forState:UIControlStateNormal];
    [_btn setBackgroundImage:[self imageWithColor:[UIColor lightGrayColor] andSize:_btn.frame.size] forState:UIControlStateDisabled];
}
- (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)aSize
{
    CGRect rect = CGRectMake(0.0f, 0.0f, aSize.width, aSize.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

- (void)btnAction:(UIButton *)sender
{
    sender.enabled = NO;
    [self refreshButtonWidth];
    [sender setTitle:[NSString stringWithFormat:@"获取验证码(%zi)", _time] forState:UIControlStateNormal];

    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timeDown) userInfo:nil repeats:YES];
}

- (void)timeDown
{
    _time --;
    if (_time == 0) {
        [_btn setTitle:@"重新获取" forState:UIControlStateNormal];
        _btn.enabled = YES;
        [self refreshButtonWidth];

        [_timer invalidate];
        _timer = nil;
        _time = 5 ;
        return;
    }
    [_btn setTitle:[NSString stringWithFormat:@"获取验证码(%zi)", _time] forState:UIControlStateNormal];
}
//第二种方法
#pragma mark -点击发送验证码
- (void)sendMessage:(UIButton *)btn
{

    if (self.phoneField.text.length == 0) {
        [self remindMessage:@"请输入正确的手机号"];

    }else{
        __block int timeout=60; //倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            if(timeout<=0){ //倒计时结束,关闭
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                设置界面的按钮显示 根据自己需求设置
                    [btn setTitle:@"发送验证码" forState:UIControlStateNormal];
                    btn.userInteractionEnabled = YES;
                });
            }else{
                int seconds = timeout % 60;
                NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
                if ([strTime isEqualToString:@"0"]) {
                    strTime = [NSString stringWithFormat:@"%d",60];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    //NSLog(@"____%@",strTime);
                    [UIView beginAnimations:nil context:nil];
                    [UIView setAnimationDuration:1];
                    [btn setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                    [UIView commitAnimations];
                    btn.userInteractionEnabled = NO;
                });
                timeout--;
            }
        });
        dispatch_resume(_timer);
}

效果图:

    1. UITextField默认占位符是居中显示,让其居上显示
 textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
  • 13.拍照,获取相机的相册,并自定义相机界面
#import "ViewController.h"

@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong)UIImagePickerController * picker;
@property (nonatomic, strong)UIImageView * imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 250, 250)];
    _imageView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.imageView];

    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(100, 350, 100, 50);
    btn.backgroundColor = [UIColor greenColor];
    [btn setTitle:@"保存图片" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(doClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
- (void)doClick:(UIButton *)sender
{
    //创建图片选择控制器对象
    self.picker = [[UIImagePickerController alloc]init];
    //设置代理
    _picker.delegate = self;
    //设置样式
    /**
     *   UIImagePickerControllerSourceTypePhotoLibrary,//从相册打开照片
     UIImagePickerControllerSourceTypeCamera,//启动摄像头拍照
     UIImagePickerControllerSourceTypeSavedPhotosAlbum//直接打开保存的照片列表,如果有摄像头,则打开相册
     */
    UIImagePickerControllerSourceType type = UIImagePickerControllerSourceTypeCamera;
    _picker.sourceType = type;
    //允许编辑(选择好图片或者拍摄好之后允许用户拖动缩放等操作)
    _picker.allowsEditing = YES;
    //弹出相机
    [self presentViewController:self.picker animated:YES completion:^{

    }];

    //自定义相机界面
    _picker.showsCameraControls = NO;

    UIToolbar * tool = [[UIToolbar  alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 40, self.view.frame.size.width, 40)];
    tool.barStyle = UIBarStyleBlackTranslucent;
    tool.barTintColor = [UIColor greenColor];

    UIBarButtonItem * cancel = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(touchCancel)];
    cancel.width = self.view.frame.size.width/2;

    UIBarButtonItem * ok = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(touchOk)];
    ok.width = self.view.frame.size.width/2;

    [tool setItems:@[cancel,ok]];
    //把自定义的view添加到UIImagePickerController的layView上
    _picker.cameraOverlayView = tool;

}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //从字典中取出照片
    /*
     UIImagePickerControllerEditedImage 编辑之后的图片
     UIImagePickerControllerOriginalImage 原来的图片
    */
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.imageView.image = image;
    //相机消失
    [self dismissViewControllerAnimated:YES completion:^{

    }];

}
#pragma mark - 取消按钮和确定按钮
- (void)touchCancel
{
    [self.picker dismissViewControllerAnimated:YES completion:^{

    }];
}
- (void)touchOk
{
    [self.picker takePicture];
}
时间: 2024-10-10 23:40:24

iOS 常用知识总结的相关文章

iOS Dev (26) 初步了解下UIColor的最常用知识

作者:CSDN 大锐哥 地址:http://blog.csdn.net/prevention - 内置的颜色有啥? // Some convenience methods to create colors. These colors will be as calibrated as possible. // These colors are cached. + (UIColor *)blackColor; // 0.0 white + (UIColor *)darkGrayColor; // 0

HTML5常用知识

今日做项目,涉及到native和H5页面的交互 1.document.readyState document.readyState:判断文档是否加载完成.firefox不支持. 这个属性是只读的,传回值有以下的可能: 0-UNINITIALIZED:XML 对象被产生,但没有任何文件被加载. 1-LOADING:加载程序进行中,但文件尚未开始解析. 2-LOADED:部分的文件已经加载且进行解析,但对象模型尚未生效. 3-INTERACTIVE:仅对已加载的部分文件有效,在此情况下,对象模型是有

iOS多线程知识总结

iOS多线程知识总结 1. iOS中苹果提供4钟方案来帮助我们实现多线程: (1) 纯C语言的pthread,偏底层,需要程序员手动管理线程的生命周期,基本不用. (2) OC语言的NSTread,需要手动管理线程生命周期,偶尔调试用来获取当前线程[NSTread currentTread/mainTread]; (3) 纯C语言的GCD(Grand Central Dispatch伟大的中枢调度器),自动管理线程生命周期,完全隐藏了Tread字眼,面向任务和队列,有同步和异步函数,自动决定开启

一篇文章普及各种ios基本知识

本文由PurpleSword(jzj1993)原创,转载请注明.原文网址 http://blog.csdn.net/jzj1993 关键字:刷机 激活 SHSH 降级 越狱 Cydia Apple Store iTunes Store iTunes 内购 行货 水货 港版 日版 美版 翻新机 IMEI/序列号/串号 三码合一 有锁 卡贴 内置卡贴 基带 注:文中图片来源于网络:本文仅从技术和知识层面讨论ios相关知识,其中涉及破解等非正当行为,请自觉遵守相关法律法规. 发现目前网络上缺乏比较全的

0524.深入浅出理解iOS常用的正则表达式—基础篇[Foundation]

参考资料:cocoachina的zys475481075的文章 几个单词 Regular  ['regj?l?] adj. 定期的:有规律的 Expression [?k'spre?(?)n; ek-] n. 表现,表示 Regular expression 正则表达式 什么是正则表达式? 用一个描述字符串去验证另一个字符串是否符合描述字符串的特征.(不严谨,可以这么理解) 思考:比如表达式"12+",描述的意思是一个1和任意个2组成的字符串,那么'12'.'122'.'122'-.都

iOS常用框架源码分析

SDWebImage NSCache 类似可变字典,线程安全,使用可变字典自定义实现缓存时需要考虑加锁和释放锁 在内存不足时NSCache会自动释放存储的对象,不需要手动干预 NSCache的key不会被复制,所以key不需要实现NSCopying协议 第三方框架 网络 1.PPNetworkHelper 对AFNetworking 3.x 与YYCache的二次封装 简单易用,包含了缓存机制,控制台可以直接打印json中文字符 2..YTKNetwork 猿题库研发团队基于AFNetworki

iOS常用控件尺寸大集合

元素控件 尺寸(pts) Window(含状态栏) 320 x 480 Status Bar的高度 20 Navigation Bar的高度 44 含Prompt的Navigation Bar的高度 74 Navigation Bar的图标 20×20(透明的png) Tool Bar的高度 44 Tool Bar的图标 20×20(透明的png) Tab Bar的高度 49 Tab Bar的图标 30×30(透明的png) 竖直时键盘的高度 216.252(iOS 5+的中文键盘) 水平时键盘

iOS 小知识-tips

--->1<--- arc的项目中使用非arc代码,则添加-fno-objc-arc: 非arc项目中使用arc代码,则添加-fobjc-arc. --->2<--- 实用的类 NSKeyedArchiver [UIScreen mainScreen] [UIDevice currentDevice] [UIFont familyNames] [UIApplication sharedApplication] [NSUserDefaults standardUserDefaults

iOS常用的加密算法

在iOS开发中,为了数据的安全经常对内容进行加密,在这儿我们对常用的加密算法进行了总结: 1.MD5 <span style="font-size:18px;">+ (NSString *)md5Hash:(NSString *)str { const char *cStr = [str UTF8String]; unsigned char result[16]; CC_MD5( cStr, strlen(cStr), result ); NSString *md5Resu