1. 程式人生 > >iOS 常用知識總結

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.設定字型和行間距
//字型
NSFontAttributeName 
//段落格式 
NSParagraphStyleAttributeName 
//字型顏色
NSForegroundColorAttributeName 
//背景顏色
NSBackgroundColorAttributeName  
//刪除線格式
NSStrikethroughStyleAttributeName
//下劃線格式
NSUnderlineStyleAttributeName     
//刪除線顏色
NSStrokeColorAttributeName       
//刪除線寬度
NSStrokeWidthAttributeName
//陰影
NSShadowAttributeName 
//設定字型和行間距
    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];
}
  • 14.Xcode 7.3版本編譯不提示自定義類名

這裡寫圖片描述

  • 15.Xcode檔案路徑
//外掛的安裝路徑
~/Library/Application Support/Developer/Shared/Xcode/Plug-ins

 //描述檔案的安裝路徑
~/Library/MobileDevice/Provisioning Profiles

 //模擬器的位置
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs 

 //文件安裝位置
/Applications/Xcode.app/Contents/Developer/Documentation/DocSets

 //自定義程式碼段的儲存路徑
~/Library/Developer/Xcode/UserData/CodeSnippets/ 
如果找不到CodeSnippets資料夾,可以自己新建一個CodeSnippets資料夾。

 //獲取家目錄路徑的函式
NSString *homeDir = NSHomeDirectory();

 //獲取Documents目錄路徑的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];

 //獲取Documents目錄路徑的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];

 //獲取tmp目錄路徑的方法
NSString *tmpDir = NSTemporaryDirectory();
  • 16.點選cell上面的button,直接刪除cell;
- (void)doDeleteBtn:(UIButton *)sender
{
    SSTableViewCell *cell = (SSCTouZhuTableViewCell *)[[[sender superview] superview]superview];
    NSIndexPath *indexPath1 = [self.tableView indexPathForCell:cell];

    [self.dataAry removeObjectAtIndex:indexPath1.row];

     [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:indexPath1.row inSection:0], nil] withRowAnimation:UITableViewRowAnimationFade];

}