你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS 常用知識總結

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.設置字體和行間距
//設置字體和行間距
    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);
}

效果圖:
這裡寫圖片描述

UITextField默認占位符是居中顯示,讓其居上顯示
 textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
13.拍照,獲取相機的相冊,並自定義相機界面
#import "ViewController.h"

@interface ViewController ()
@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 *)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];
}
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved