1.NSIndexPath初始化
NSIndexPath*indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
2.監(jiān)聽(tīng)textField輸入字符串長(zhǎng)度
[textaddTarget:selfaction:@selector(textFieldDidChange:)forControlEvents:UIControlEventEditingChanged];
-(void)textFieldDidChange :(UITextField*)theTextField{
if(theTextField.text.length==11) {
}
}
3.iOS去除Plain樣式TableView底部多余的分割線
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
4.導(dǎo)航欄pop回指定控制器
for(UIViewController*temp in self.navigationController.viewControllers) {
if([temp isKindOfClass:NSClassFromString(@"xx")]) {
[self.navigationControllerpopToViewController:tempanimated:YES];
}
}
UIViewController *viewCtl = self.navigationController.viewControllers[2];
[self.navigationController popToViewController:viewCtl animated:YES];
5.兩個(gè)或多個(gè)網(wǎng)絡(luò)請(qǐng)求区匣,全部返回后才可進(jìn)行下一步操作(比如刷新頁(yè)面UI等)掰担,需搭配使用線程組以及信號(hào)量
dispatch_group_t lxgGroup = dispatch_group_create();/* 創(chuàng)建多線程組 */
/* 創(chuàng)建并行隊(duì)列 */
dispatch_queue_t queue = dispatch_queue_create(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
/*異步執(zhí)行任務(wù)*/
dispatch_group_async(lxgGroup, queue, ^{
[self loadData:lxg parms:@"10059" data:dic];
});
dispatch_group_async(lxgGroup, queue, ^{
[self loadTwoData:lxg parms:@"10231" data:dic];
});
/*線程組內(nèi)任務(wù)執(zhí)行完畢,獲取通知*/
dispatch_group_notify(lxgGroup, dispatch_get_main_queue(), ^{
[self.table reloadData];
[self.view hideHUD];
[self.table.mj_header endRefreshing];
});
- (void)loadData:(LXGNetWorkQuery*)lxg parms:(NSString*)parms data:(NSMutableDictionary*)dic
{
dispatch_semaphore_t sema = dispatch_semaphore_create(0);/* 創(chuàng)建信號(hào)量 */
[lxg AFrequestData:parms
HttpMethod:@"POST"
params:dic
completionHandle:^(id result) {
dispatch_semaphore_signal(sema);/* 發(fā)送信號(hào)量 */
} errorHandle:^(NSError *result) {
[self.view showError:@"網(wǎng)絡(luò)錯(cuò)誤"];
dispatch_semaphore_signal(sema);/* 發(fā)送信號(hào)量 */
}];
/* 等待信號(hào)倔叼,相當(dāng)于堵塞線程亭姥、和線程鎖功能相似 */
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
6.刪除單元格方法及注意事項(xiàng)
[tableView deleteRowsAtIndexPaths:
[NSArray arrayWithObject:indexPath] withRowAnimation:
UITableViewRowAnimationLeft];
/**此方法為刪除一行cell的方法麻裳,同步刪除數(shù)據(jù)源這種操作就不提了庆寺,
有個(gè)坑點(diǎn)就是柿究,如果刪除的本行cell,是這一組的最后一個(gè)cell孤里,切記一定要調(diào)用下面的方法刪除本組伏伯,否則會(huì)崩潰*/
[tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationLeft];
7.設(shè)置Lable部分文字屬性(文字大小,顏色)
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@元",_model.price]];
// 設(shè)置顏色
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(9, _model.price.length+1)];
//設(shè)置文字大小
[string addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:35]
range:NSMakeRange(0 , _model.price.length)];
_priceLable.attributedText = string;
8.將顏色轉(zhuǎn)成圖片
- (UIImage *)createImageWithColor:(UIColor *)color
{
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 *myImage =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return myImage;
}
9.UILable大小計(jì)算方法
CGSize titleSize = [str boundingRectWithSize:CGSizeMake((Screen_width-30),MAXFLOAT)options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}context:nil].size;
10.RunTime交換方法初級(jí)使用
應(yīng)用場(chǎng)景是這樣的:A頁(yè)面有一個(gè)GCD定時(shí)器捌袜,控制A頁(yè)面lable的秒數(shù)跳動(dòng)说搅,此時(shí)需要跳轉(zhuǎn)到B頁(yè)面,B頁(yè)面也有一個(gè)lable需要同步跳動(dòng)虏等,現(xiàn)在需要A跳轉(zhuǎn)的B頁(yè)面后弄唧,A的定時(shí)器控制B頁(yè)面lable的跳動(dòng),當(dāng)返回A頁(yè)面的時(shí)候則定時(shí)器控制A頁(yè)面lable跳動(dòng)霍衫。代碼如下:
//本頁(yè)面開(kāi)啟定時(shí)器
- (void)startTime
{
// GCD定時(shí)器
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_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); //每秒執(zhí)行
WEAKSELF;
dispatch_source_set_event_handler(_timer, ^{
[weakSelf quesstionTimeAction];
});
// 開(kāi)啟定時(shí)器
dispatch_resume(_timer);
}
/** 跳轉(zhuǎn)到下一個(gè)頁(yè)面 */
- (void)dtkAction
{
AnswerSheetCtr*answer = [[AnswerSheetCtr alloc] init];
UILabel*titleLable = (UILabel*)self.navigationItem.titleView;
answer.time = titleLable.text;
[self.navigationController pushViewController:answer animated:YES];
WEAKSELF;
[answer setBlock:^{
// 返回本頁(yè)面后再次交換定時(shí)器方法
[weakSelf exChangeFunction];
}];
[self exChangeFunction];
}
/** 交換定時(shí)器方法候引,跳轉(zhuǎn)到答題卡頁(yè)面前,定時(shí)器控制本頁(yè)面的時(shí)間跳動(dòng)敦跌,跳轉(zhuǎn)到答題卡后澄干,定時(shí)器控制答題卡頁(yè)面時(shí)間跳動(dòng) */
- (void)exChangeFunction
{
Method method1 = class_getInstanceMethod([QuestionController class], @selector(quesstionTimeAction));
Method method2 = class_getInstanceMethod([QuestionController class], @selector(questionAnswerAction));
method_exchangeImplementations(method1, method2);
}
11.sizeToFit與sizeThatFits的使用和區(qū)別
sizeToFit會(huì)自動(dòng)算出lable的size,并且調(diào)用sizeToFit會(huì)自動(dòng)改變自身size
sizeThatFits也會(huì)自動(dòng)算出size柠傍,但是不會(huì)自動(dòng)改變自身size
12.cocopods新源域名:https://gems.ruby-china.com/
13.替換工程內(nèi)所有Lable的部分文字
+ (void)initialize
{
Method setText =class_getInstanceMethod([UILabel class], @selector(setText:));
Method setTextMySelf =class_getInstanceMethod([self class],@selector(setTextHooked:));
// 將目標(biāo)函數(shù)的原實(shí)現(xiàn)綁定到setTextOriginalImplemention方法上
IMP setTextImp =method_getImplementation(setText);
class_addMethod([UILabel class], @selector(setTextOriginal:), setTextImp,method_getTypeEncoding(setText));
//然后用我們自己的函數(shù)的實(shí)現(xiàn)麸俘,替換目標(biāo)函數(shù)對(duì)應(yīng)的實(shí)現(xiàn)
IMP setTextMySelfImp =method_getImplementation(setTextMySelf);
class_replaceMethod([UILabel class], @selector(setText:), setTextMySelfImp,method_getTypeEncoding(setText));
}
- (void)setTextHooked:(NSString *)string
{
string = [string stringByReplacingOccurrencesOfString:@"測(cè)試" withString:@"小剛"];
[self performSelector:@selector(setTextOriginal:) withObject:string];
}
14.圖片文件壓縮
//文件壓縮(包含圖片文件壓縮,類似于ZIP惧笛、RARg格式的壓縮从媚,只縮小文件大小,不會(huì)失幀患整,加載圖片的時(shí)候會(huì)還原圖片大小静檬,所以一般只用于存儲(chǔ)、上傳)
- (void)fileCompression
{
UIImage*oldImage = [UIImage imageNamed:@"XX"];
/* 此處轉(zhuǎn)換圖片為data格式 */
NSData*oldData = UIImagePNGRepresentation(oldImage);
NSString*oldImageLength = [self getImageLength:oldData.length];
/* 此處壓縮圖片為jpg的data并级,文件體積比png會(huì)更小 */
NSData*newData = UIImageJPEGRepresentation(oldImage, 1);
NSString*newImageLength = [self getImageLength:newData.length];
NSLog(@"%@=====%@",oldImageLength,newImageLength);
CGFloat xRate = 1;
//比如說(shuō)拂檩,希望圖片文件壓縮到50KB,xRate為壓縮倍數(shù)示例嘲碧,其實(shí)在實(shí)際使用中可以直接使用確定的常量
while (newData.length > 50*1024) {
xRate -= 0.1;
//一直壓縮到50KB以下為止
newData = UIImageJPEGRepresentation(oldImage, xRate);
if (xRate < 0.1) {
break;
}
}
/* 最后根據(jù)壓縮的data獲取圖片稻励,或者直接進(jìn)行上傳、存儲(chǔ)等操作 */
oldImage = [UIImage imageWithData:newData];
}
//此處獲取圖片長(zhǎng)度
- (NSString*)getImageLength:(long)length
{
NSString*backStr = nil;
float size_kb = length/1024.0;
if (size_kb <1024) {
backStr = [NSString stringWithFormat:@"%0.2fkb",size_kb];
}else
{
backStr = [NSString stringWithFormat:@"%0.2fMB",size_kb/1024];
}
return backStr;
}
15.圖片加載優(yōu)化處理
假設(shè)有一張圖片,大小是1.6MB望抽,圖片尺寸是3096X4128加矛,使用“imageNamed”的圖片加載方式進(jìn)行加載,最后會(huì)占用手機(jī)多少內(nèi)存呢煤篙?答案是48MB之多U謇馈(圖片上一個(gè)像素是RGBA,也就是4個(gè)字節(jié)辑奈,4bytes * 3096 * 4128 = 48MB)試想多加載幾張這樣的大圖片苛茂,APP必然會(huì)因?yàn)閮?nèi)存吃緊被殺掉,那么有什么方法解決呢鸠窗?(不考慮imageWithContentsOfFile的方式)
//第一種圖片處理方式妓羊,通過(guò)圖片上下文做文章,此種方法盡量在主線程操作,比較耗費(fèi)CPU稍计,多張圖片處理可能造成線程堵塞
- (void)scaleImage{
//取出一個(gè)3024*3024尺寸的圖片
UIImage*image = [UIImage imageWithContentsOfFile:@"3024*3024"];
//改成200*200尺寸
CGSize imageSize = CGSizeMake(200, 200);
//開(kāi)啟圖片上下文
UIGraphicsBeginImageContext(imageSize);
//更改
[image drawInRect:CGRectMake(0, 0, 200, 200)];
//生成新的圖片
UIImage*newImage = UIGraphicsGetImageFromCurrentImageContext();
//關(guān)閉上下文
UIGraphicsEndImageContext();
}
//第二種圖片處理方式躁绸,可放入子線程
- (void)scaleImageThead{
//取出一個(gè)3024*3024尺寸的圖片
UIImage*image = [UIImage imageWithContentsOfFile:@"3024*3024"];
CGFloat width = 100;
CGFloat height = 100;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();//顏色空間
NSUInteger bytesPerPixel = 4;//RGBA 是4個(gè)字節(jié),所以此處填4
NSUInteger bytesPerRow = bytesPerPixel*width;//這一行是多少字節(jié)臣嚣,就是4*圖片寬度
NSUInteger bitsPerComPonent = 8;
//生成上下文
CGContextRef context = CGBitmapContextCreate(nil, width, height, bitsPerComPonent, bytesPerRow, colorSpaceRef, kCGBitmapByteOrderDefault|kCGImageAlphaPremultipliedLast);
//根據(jù)上下文净刮、圖片、位置硅则、生成新圖片淹父,注意此處如果不做處理,坐標(biāo)會(huì)與正常坐標(biāo)系相反抢埋,下文使用UIImageOrientationUp屬性,確定了圖片的方向
CGContextDrawImage(context, CGRectMake(0, 0, width, height), image.CGImage);
CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage*newImage = [UIImage imageWithCGImage:imageRef scale:UIScreen.mainScreen.scale orientation:UIImageOrientationUp];
}
16.關(guān)于tableView知識(shí)點(diǎn)的小tag,在tableView只有tableHeaderView而沒(méi)有cell的時(shí)候 tableView是不能滑動(dòng)的(即沒(méi)有數(shù)據(jù)的時(shí)候)督暂,如果要滑動(dòng)揪垄,需要添加一個(gè)cell(可以使用默認(rèn)圖點(diǎn)擊刷新的方法,或者加一個(gè)高度為0.01的透明cell)
17.個(gè)數(shù)相同的時(shí)候逻翁,數(shù)字饥努、文字不對(duì)齊,可以考慮字體用等寬字體:
[UIFont monospacedDigitSystemFontOfSize:11 weight:UIFontWeightMedium];