前言
記錄一些代碼小技巧持續更新!
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 = @"我是 Tate-zwt";
replaceStr = [replaceStr stringByReplacingOccurrencesOfString:@" " 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設置