iOS Develop Tips

前言

記錄一些代碼小技巧持續更新!

Xcode12模板位置:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File Templates/iOS/Source/Cocoa Touch Class.xctemplate
Objective-C tips

1、使控件從導航欄以下開始

 self.edgesForExtendedLayout=UIRectEdgeNone;

2、將navigation返回按鈕文字position設置不在屏幕上顯示

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];

3、解決ScrollView等在viewController無法滾動到最頂部

//自動滾動調整,默認為YES
self.automaticallyAdjustsScrollViewInsets = NO;

4、隱藏navigationBar上返回按鈕

[self.navigationController.navigationItem setHidesBackButton:YES];
[self.navigationItem setHidesBackButton:YES];
[self.navigationController.navigationBar.backItem setHidesBackButton:YES];

5、當tableView占不滿一屏時,去除上下邊多余的單元格

self.tableView.tableHeaderView = [UIView new];
self.tableView.tableFooterView = [UIView new];

6、顯示完整的CellSeparator線

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

7、滑動的時候隱藏navigation bar

navigationController.hidesBarsOnSwipe = Yes;

8、將Navigationbar變成透明而不模糊

[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
                         forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar .shadowImage = [UIImage new];
self.navigationController.navigationBar .translucent = YES;

9、NSString常用處理方法

//截取字符串
NSString *interceptStr1 = @"Tate_zwt";
interceptStr1 = [interceptStr1 substringToIndex:3];//截取下標3之前的字符串
NSLog(@"截取的值為:%@",interceptStr1);//截取的值為:Tat

NSString *interceptStr2 = @"Tate_zwt";
NSRange rang = {3,1};
interceptStr2 = [interceptStr2 substringWithRange:rang];//截取rang范圍的字符串
NSLog(@"截取的值為:%@",interceptStr2);//截取的值為:e

NSString *interceptStr3 = @"Tate_zwt";
interceptStr3 = [interceptStr3 substringFromIndex:3];//截取下標3之后的字符串
NSLog(@"截取的值為:%@",interceptStr3);//截取的值為:e_zwt


//匹配字符串
NSString *matchingStr = @"Tate_zwt";
NSRange range = [matchingStr rangeOfString:@"t"];//匹配得到的下標
NSLog(@"rang:%@",NSStringFromRange(range));//rang:{2, 1}
matchingStr = [matchingStr substringWithRange:range];//截取范圍類的字符串
NSLog(@"截取的值為:%@",matchingStr);//截取的值為:t


//分割字符串
NSString *splitStr = @"Tate_zwt_zwt";
NSArray *array = [splitStr componentsSeparatedByString:@"_"]; //從字符A中分隔成2個元素的數組
NSLog(@"array:%@",array); //輸出3個對象分別是:Tate,zwt,zwt


//拼接字符串
NSMutableString *appendStr =  [NSMutableString string];
//使用逗號拼接
//[append appendFormat:@"%@zwt", append.length ? @"," : @""];
[appendStr appendString:@"我是"];
[appendStr appendString:@"Tate-zwt"];
NSLog(@"%@",appendStr);//輸出:我是Tate-zwt


//替換字符串
NSString *replaceStr = @"我是&nbspTate-zwt";
replaceStr = [replaceStr stringByReplacingOccurrencesOfString:@"&nbsp" withString:@""];
NSLog(@"%@",replaceStr);//輸出:我是Tate-zwt
        
        
//判斷字符串內是否還包含特定的字符串(前綴,后綴)
NSString *hasStr = @"Tate.zwt";
[hasStr hasPrefix:@"Tate"] == 1 ?  NSLog(@"YES") : NSLog(@"NO"); //前綴
[hasStr hasSuffix:@".zwt"] == 1 ?  NSLog(@"YES") : NSLog(@"NO"); // 后綴


//字符串是否包含特定的字符
NSString *containStr = @"iOS Developer,喜歡做有趣的產品";
NSRange rangeDeveloper = [containStr rangeOfString:@"Developer"];
NSRange rangeProduct = [containStr rangeOfString:@"Product"];
rangeDeveloper.location != NSNotFound == 1 ?  NSLog(@"YES") : NSLog(@"NO");
rangeProduct.location != NSNotFound == 1 ?  NSLog(@"YES") : NSLog(@"NO");

10、UIPageControl如何改變點的大小?
重寫setCurrentPage方法即可:

- (void)setCurrentPage:(NSInteger)page {
    [super setCurrentPage:page];
    for (NSUInteger subviewIndex = 0; subviewIndex < [self.subviews count]; subviewIndex++) {
        UIView *subview = [self.subviews objectAtIndex:subviewIndex];
        UIImageView *imageView = nil;
        if (subviewIndex == page) {
            CGFloat w = 8;
            CGFloat h = 8;
            imageView = [[UIImageView alloc] initWithFrame:CGRectMake(-1.5, -1.5, w, h)];
            imageView.image = [UIImage imageNamed:@"banner_red"];
            [subview setFrame:CGRectMake(subview.frame.origin.x, subview.frame.origin.y, w, h)];
        } else {
            CGFloat w = 5;
            CGFloat h = 5;
            imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, w, h)];
            imageView.image = [UIImage imageNamed:@"banner_gray"];
            [subview setFrame:CGRectMake(subview.frame.origin.x, subview.frame.origin.y, w, h)];
        }
        imageView.tag = 10010;
        UIImageView *lastImageView = (UIImageView *) [subview viewWithTag:10010];
        [lastImageView removeFromSuperview]; //把上一次添加的view移除
        [subview addSubview:imageView];
    }
}

11、如何改變多行UILabel的行高?
Show me the code:

    _promptLabel = [UILabel new];
    NSString *labelText = @"Talk is cheap\nShow me the code";
    _promptLabel.text = labelText;
    _promptLabel.numberOfLines = 2;
    _promptLabel.font = [UIFont systemFontOfSize:14];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:10]; //調整行間距
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
    _promptLabel.attributedText = attributedString;
    [_promptLabel sizeToFit];
    [self.view addSubview:_promptLabel];

12、如何讓Label等控件支持HTML格式的代碼?
使用NSAttributedString:

NSString *htmlString = @"<div>Tate<span style='color:#1C86EE;'>《iOS Develop Tips》</span>get <span style='color:#1C86EE;'>Tate_zwt</span> 打賞 <span style='color:#FF3E96;'>100</span> 金幣</div>";
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:nil error:nil];
_contentLabel.attributedText = attributedString;

13、如何讓Label等控件同時支持HTML代碼和行間距?

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[_open_bonus_article dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:nil error:nil];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:12]; //調整行間距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attributedString length])];
_detailLabel.attributedText = attributedString;
[_detailLabel sizeToFit];

14、pop回根控制器視圖

//這里也可以指定pop到哪個索引控制器
[self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] - 3)] animated:YES];
//或者
[self.navigationController popToRootViewControllerAnimated:YES];

15、dismiss回根控制器視圖(PS:只能返回兩層)

if ([self respondsToSelector:@selector(presentingViewController)]){
self.presentingViewController.view.alpha = 0;
[self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
 }else {
self.parentViewController.view.alpha = 0;
[self.parentViewController.parentViewController dismissViewControllerAnimated:YES completion:nil];
 }
//或者
if ([self respondsToSelector:@selector(presentingViewController)]){
[self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}else {
[self.parentViewController.parentViewController dismissViewControllerAnimated:YES completion:nil];
}

16、兩個控制器怎么無限push?

NSMutableArray *vcArr = [self.navigationController.viewControllers mutableCopy];
[vcArr removeLastObject];
[vcArr addObject:loginVC];
[self.navigationController setViewControllers:vcArr animated:YES];

17、NSDictionary 怎么轉成NSString

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:response.data options:0 error:0];
NSString *dataStr =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

18、獲取系統可用存儲空間 ,單位:字節

/**
 *  獲取系統可用存儲空間
 *
 *  @return 系統空用存儲空間,單位:字節
 */
-(NSUInteger)systemFreeSpace{
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSDictionary *dict=[[NSFileManager defaultManager] attributesOfFileSystemForPath:docPath error:nil];
    return [[dict objectForKey:NSFileSystemFreeSize] integerValue];
}

19、有時OC調用JS代碼沒反應?
stringByEvaluatingJavaScriptFromString 必須在主線程里執行

dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.webView stringByEvaluatingJavaScriptFromString:jsStr];
//            [weakSelf.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"alertTest('%@');", @"test"]];
        });

20、獲取相冊圖片的名稱及后綴

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//獲取圖片的名字
     __block NSString* fileName;
    NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
        ALAssetRepresentation *representation = [myasset defaultRepresentation];
        fileName = [representation filename];
        NSLog(@"fileName : %@",fileName);
        self.imageFileName = fileName;
    };
    
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    [assetslibrary assetForURL:imageURL
                   resultBlock:resultblock
                  failureBlock:nil];
}

21、UITableView 自動滑動到某一行

//四種枚舉樣式
UITableViewScrollPositionNone,
UITableViewScrollPositionTop,
UITableViewScrollPositionMiddle,
UITableViewScrollPositionBottom

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//第一種方法
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
//第二種方法
[self.tableVieW selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];

22、 Xcode8注釋快捷鍵不能使用的解決方法:
In Terminal: sudo /usr/libexec/xpccachectl

最近使用CocoaPods來添加第三方類庫,無論是執行pod install還是pod update都卡在了Analyzing dependencies不動
原因在于當執行以上兩個命令的時候會升級CocoaPods的spec倉庫,加一個參數可以省略這一步,然后速度就會提升不少。加參數的命令如下:

pod install --verbose --no-repo-update
pod update --verbose --no-repo-update

你可以 cd ~/.cocoapods/repos/ 到這個目錄下 執行du -sh * 看下下載了多少

23、獲取模擬器沙盒路徑

NSArray *aryPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//沙盒路勁
NSString *strDocPath=[aryPath objectAtIndex:0];

24、tableView.tableHeaderView 一些設置方法

    _tableView.tableHeaderView = _heatOrTimeView;
    [_heatOrTimeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(_tableView);
        make.width.equalTo(_tableView);
        make.height.mas_equalTo(@36);
    }];
//    如果是動態改變高度的話這里要加上以下代碼
//    [_tableView layoutIfNeeded];
//    [_tableView beginUpdates]; 這個是增加動畫效果
//    [_tableView endUpdates];
//    _tableView.tableHeaderView = _heatOrTimeView;

25、約束如何做UIView動畫?

1、把需要改的約束Constraint拖條線出來,成為屬性
2、在需要動畫的地方加入代碼,改變此屬性的constant屬性
3、開始做UIView動畫,動畫里邊調用layoutIfNeeded方法

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttonTopConstraint;
self.buttonTopConstraint.constant = 100;
    [UIView animateWithDuration:.5 animations:^{
        [self.view layoutIfNeeded];
    }];

26、刪除某個view所有的子視圖

[[someView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];

27、將一個view放置在其兄弟視圖的最上面

[parentView bringSubviewToFront:yourView]

28、將一個view放置在其兄弟視圖的最下面

[parentView sendSubviewToBack:yourView]

29、layoutSubviews方法什么時候調用?

1、init方法不會調用
2、addSubview方法等時候會調用
3、bounds改變的時候調用
4、scrollView滾動的時候會調用scrollView的layoutSubviews方法(所以不建議在scrollView的layoutSubviews方法中做復雜邏輯)
5、旋轉設備的時候調用
6、子視圖被移除的時候調用參考請看:[http://blog.logichigh.com/2011/03/16/when-does-layoutsubviews-get-called/](http://blog.logichigh.com/2011/03/16/when-does-layoutsubviews-get-called/)

30、isKindOfClass和isMemberOfClass的區別

isKindOfClass可以判斷某個對象是否屬于某個類,或者這個類的子類。
isMemberOfClass更加精準,它只能判斷這個對象類型是否為這個類(不能判斷子類)

31、IOS App開啟iTunes文件共享(文稿)

通過在app工程的Info.plist文件中指定Application supports iTunes file sharing關鍵字,并將其值設置為YES。
我們可以很方便的打開app與iTunes之間的文件共享。
但這種共享有一個前提:App必須將任何所需要共享給用戶的文件,都要存放在<Application_Home>/Documents目錄下,<Application_Home>即在app安裝時自動創建的app的主目錄。

32、去掉UITabBar的分割線的方法

[[UITabBar appearance] setShadowImage:[UIImage new]];
[[UITabBar appearance] setBackgroundImage:[UIImage new]];

33、URLWithString:(NSString *)str relativeToURL:(NSURL *)baseURL中baseURL拼接字段的問題
問題描述
URLWithString:(NSString *)str relativeToURL:(NSURL *)baseURL中baseURL結尾字段的相關問題拼接后被去掉的問題,情況如下:

NSURL *baseUrl = [NSURL URLWithString:@"http://test.com/v1"];
NSLog(@"%@", baseUrl);
NSURL *newURL = [NSURL URLWithString:@"/test/get_all" relativeToURL: baseUrl];
NSLog(@"newURL:%@",[newURL absoluteString]);//http://test.com/test/get_all

其中v1字符串拼接后被去掉了
解決辦法:
直接讓baseUrl已/符號結尾

NSURL *baseUrl = [NSURL URLWithString:@"http://test.com/v1/"];
NSLog(@"%@", baseUrl);
NSURL *newURL = [NSURL URLWithString:@"test/get_all" relativeToURL: baseUrl];
NSLog(@"newURL:%@",[newURL absoluteString]);//http://test.com/v1/test/get_all

34、URL編碼 、解碼
編碼:iOS中http請求遇到漢字的時候,需要轉化成UTF-8,用到的方法是:

NSString *result = [sns_info stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];

解碼:請求后,返回的數據,如何顯示的是這樣的格式:%3A%2F%2F,此時需要我們進行UTF-8解碼,用到的方法是:

NSString *resultData = result.stringByRemovingPercentEncoding;

35、reactiveCocoa rac_signalForControlEvents多次觸發解決方法
原因:
我們知道cell在移出屏幕時并沒有被銷毀,而是到了一個重用池中,放到池子前我們已經做了[[cell.btn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(idx) {}];
,取不到的話再創建。所以取出來的cell極有可能是池子里的,取出來之后再進行上述的rac_signalForControlEvents操作,導致每rac_signalForControlEvents多少次操,點擊按鈕時,事件就被觸發多少次!
此時就得通過takeUntil:someSignal來終止cell.btn之前的signal了:
解決:

[[_cell.btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
    }];

換成

[[[cell.deleteBtn rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
    }];

36、一個Label 顯示兩種顏色的寫法

NSAttributedString *commentCountAttrString = [[NSAttributedString alloc] initWithString:@"回復:" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:CFontColor3}];
        NSMutableAttributedString *commentAttrString = [[NSMutableAttributedString alloc] initWithString:_messageModel.content attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14],NSForegroundColorAttributeName:CFontColor5}];
        NSMutableAttributedString *commentString = [[NSMutableAttributedString alloc] init];
        [commentString appendAttributedString: commentCountAttrString];
        [commentString appendAttributedString: commentAttrString];
        _replyLabel.attributedText = commentString;

37、解決iPhone 橫屏啟動界面錯亂的問題
在AppDelegate中,在didFinishLaunchingWithOptions方法中創建window前先加入:

application.statusBarOrientation = UIInterfaceOrientationPortrait;

38、iPhone 屏幕亮度

//獲取系統屏幕當前的亮度值
CGFloat value = [UIScreen mainScreen].brightness;
//設置系統屏幕的亮度值
[[UIScreen mainScreen] setBrightness:value];

38、如何讓在UIScrollView的vc移動時也能調用生命周期?
手動調用VC的生命周期:

    NSInteger currentIndex = contentOffset.x/self.frame.size.width;
    UIViewController *oldVC = nil;
    if (currentIndex != -1) {
        oldVC = _viewsArray[currentIndex];
    }
    UIViewController *newsVc = _viewsArray[currentIndex];
    if (newsVc.view.superview)  {//調用生命周期函數(如viewwillappear等)
        if (oldVC) {
            [newsVc beginAppearanceTransition:NO animated:YES];
            [newsVc endAppearanceTransition];
        }
        [newsVc beginAppearanceTransition:YES animated:YES];
        [newsVc endAppearanceTransition];
    }

39、常用C語言函數

一.隨機數:

1.rand();

范圍:        0-無窮大.

特點:        僅第一次隨機,其他次都是和第一次相同.常用于調試.

返回值:     long

實例:        int ran = rand(); 

2.random();

范圍:        0-無窮大.

特點:        每次都隨機出現一個數字

返回值:     long

二: 絕對值:

1.abs(int);

特點:        整數的絕對值

返回值:     int

實例:        int ab = abs(-1);

2.fabs(double);

特點:        浮點數的絕對值

返回值:     double

實例:        double fab = fabs(-12.345);

三: 取整

1.trunc(double);

特點:        直接取整

返回值:     double

實例:        double tru = trunc(3.444);

2.ceil(double)

特點:        向上取整 (舍棄小數點部分,往個位數進1)

返回值:     double

實例:        double ce = ceil(12.345);

3.floor(double);

特點:        向下取整 (舍棄小數點部分)

返回值:     double

實例:        double flo = floor(12.345);

4.四舍五入

實現方法:巧妙的利用取整規則

說明: a是要四舍五入的數,b是結果

(1)如果取整的是正數:

    CGFloat a = 1.5;

    int b = (int)(a + 0.5);

(2)如果取整的是負數:

    CGFloat a = -1.5;

    int b = (int)(a - 0.5);

5.浮點數提取整數和小數

    double fraction,integer;

    double number = 100000.567;

    fraction = modf(number, &integer);

    printf("The whole and fractional parts of %lf are %lf and %lf",number, integer, fraction);

四: 算數相關

1.pow(double, double);

特點:        求a的b次方

返回值:     double

實例:        double po = pow(2, 3);

2.sqrt(double)

特點:        求平方根

返回值:     double

實例:        double sqr = sqrt(2);

五:圓周率

     M_PI      ==  π

     M_PI_2    ==  π/2

     M_PI_4    ==  π/4

     M_1_PI    ==  1/π

     M_2_PI    ==  1/2

六.比較大小

1.MAX(1, 2);  返回最大值

2.MIN(2, 1);  返回最小值

3.ABS(-2);    返回絕對值

40、UILable 樣式自定義(同一個Label展示不同顏色,字體)

 //拼接字符串
        NSMutableString *appendStr =  [NSMutableString string];
        [appendStr appendString:@"摘要:"];
        [appendStr appendString:_movies.editor_note];

        NSMutableAttributedString *noteStr =  [YYPublicTools load_attributedString:appendStr font:FFont4 color:CFontColor4 Alignment:NSTextAlignmentLeft];
        NSRange redRange = NSMakeRange([[noteStr string] rangeOfString:@"摘要:"].location, [[noteStr string] rangeOfString:@"摘要:"].length);
        //需要設置的位置
        [noteStr addAttribute:NSForegroundColorAttributeName value:CFontColor3 range:redRange];
        [noteStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:redRange];
        //設置
        _authorSayLabel.attributedText = noteStr;
+ (NSMutableAttributedString *)load_attributedString:(NSString *)string font:(UIFont *)font color:(UIColor *)color Alignment:(NSTextAlignment )Alignment{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[string dataUsingEncoding:NSUnicodeStringEncoding] options:@{} documentAttributes:nil error:nil];
    
    NSMutableParagraphStyle * paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle1 setLineSpacing:7];
    [paragraphStyle1 setAlignment:Alignment];
    NSDictionary *attributeDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   font,NSFontAttributeName,
                                   paragraphStyle1,NSParagraphStyleAttributeName,color,NSForegroundColorAttributeName,nil];
    [attributedString addAttributes:attributeDict range:NSMakeRange(0, [attributedString length])];
    return attributedString;
}

41、解決IQKeyboardManager在UITableviewCell中TextField或者TextView不起作用的問題。
框架本身不支持所以只能用代碼解決:
1.首先在- (void)viewDidLoad中調用對鍵盤實現監聽

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

2.然后調用通知的方法:

#pragma mark 鍵盤出現
-(void)keyboardWillShow:(NSNotification *)note
{
    CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, keyBoardRect.size.height, 0);
}
#pragma mark 鍵盤消失
-(void)keyboardWillHide:(NSNotification *)note
{
    self.tableView.contentInset = UIEdgeInsetsZero;
}

42、去除字符串首尾空格、換行

//去除首尾空格和換行 
//NSCharacterSet 多個枚舉選擇
NSString *content = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

43、autolayout進階

1.Content Hugging Priority

視圖抗拉伸優先級, 值越小,視圖越容易被拉伸,

2. Content Compression Resistance Priority:

視圖抗壓縮優先級, 值越小,視圖越容易被壓縮,

44、pod 單獨安裝一個新添加的庫
這將安裝新項目而不更新現有的repos
pod install --no-repo-update

45、iOS-限制UILabel寬度自適應的最大寬度

_userNameLabel.preferredMaxLayoutWidth = 170 * kScaleWidth; //設置多行label最大寬度,只在 numberOfLines = 0 生效
_userNameLabel.numberOfLines = 0; //可在xib 或者 Sb設置
_userNameLabel.height = 20; // 讓他固定只能一行的高度 可在xib 或者 Sb設置
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,619評論 6 539
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,155評論 3 425
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,635評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,539評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,255評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,646評論 1 326
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,655評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,838評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,399評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,146評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,338評論 1 372
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,893評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,565評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,983評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,257評論 1 292
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,059評論 3 397
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,296評論 2 376

推薦閱讀更多精彩內容

  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一種新的協議。它實...
    香橙柚子閱讀 24,008評論 8 183
  • 文/邊緣 (東山) 一 我想,我的心是被烏...
    邊緣AA閱讀 1,067評論 0 6
  • 平遙點悟 其實就和這次去平遙城里逛來逛去的,就看到了好多背后的東西,比如平遙城的規模是個什么概念,以目前平遙縣的經...
    鐵刺猬閱讀 231評論 0 1
  • 點擊進入愛加親子交流茶話會之青春期孩子相關問題 前兩天,一位14歲孩子的媽媽找到我,他的孩子今年初三了,馬上要面臨...
    廖小慷閱讀 1,065評論 0 4