自己到現(xiàn)在畢業(yè)一年,總結(jié)了自己在前段時間開發(fā)當中遇到的的一些細節(jié)問題膘滨,水平有限嘀掸,希望有可以幫助大家的
1,在OC中使用 “%s,__func__”打印出類名和方法例如:
NSlog(@“%s”,__func__);??
打印出 -[Person dealloc]
2赡鲜,RunLoopa內(nèi)部實現(xiàn)原理:
內(nèi)部由do-while循環(huán)實現(xiàn)
作用:1,保證程序的持續(xù)運行 2,處理各種APP事件(滑動庐船,定時器银酬,selector)3,節(jié)省cpu資源筐钟,提高性能
Runloop與線程 ??
? ? 1揩瞪,每條線程都有一個唯一的與之對應(yīng)的RunLoop對象? ? ? 2,主線程的Runloop隨著程序已自動創(chuàng)建好篓冲,但是子線程的Runloop需要手動創(chuàng)建李破。? 3,獲得主線程的Runloop方法是[NSRunloop mainRunloop];? ? 4壹将,創(chuàng)建子線程的Runloop方法時[NSRunLoop currentRunloop];
Runloop相關(guān)類:
1嗤攻,CFRunLoopModeRef:? 代表了RunLoop的運行模式,一個RunLoop可以包含若干個Mode诽俯,每個Mode包含若干個Source/Timer/Observer,每個RunLoop啟東時妇菱,只能指定其中的一個Mode,這個Mode被稱作currentMode。
主要的幾個Mode:KCFRunLoopDefaultMode:APP的默認Mode闯团,通常主線程是在該Mode下運行的UITrackingRunLoopMode:界面追蹤Mode辛臊,用于ScrollView追蹤觸摸滑動,保證界面滑動時偷俭,不受其他Mode影響KCFRunLoopCommonModes:這是一個占位用的Mode浪讳,不是真正的Mode,2,CFRunLoopSourceRef 3. CFRunLoopTimerRef 4, CFRunLoopObserverRef
3,定時器(NSTimer)定時器的創(chuàng)建:??
? self.timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(move) userInfo:nil repeats:YES];
定時器的銷毀:?
[self.timer invalidate];? ? self.timer = nil; (必須將銷毀的對象置為nil涌萤,否則會運行程序會報錯)
4,貝賽爾曲線的簡單設(shè)置聲明:
?UIBezierPath *bezierPath = [UIBezierPath bezierPath];
顏色的填充:[[UIColor cyanColor] set];
-(void)set:設(shè)置顏色淹遵,在當前繪制上下文中設(shè)置填充和線段顏色
-(void)setFill:設(shè)置填充
-(void)setStroke:設(shè)置線段
5,判斷app是否第一次啟動或者更新后的第一次啟動
1 #define LAST_RUN_VERSION_KEY @"last_run_version_of_application"?
?- (BOOL) isFirstLoad{?
?NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleShortVersionString"];? ??
?NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];?
NSString *lastRunVersion = [defaults objectForKey:LAST_RUN_VERSION_KEY];??
?if (!lastRunVersion) {
? [defaults setObject:currentVersion forKey:LAST_RUN_VERSION_KEY];??
return YES; ?
}??
else if (![lastRunVersion isEqualToString:currentVersion]) { ?
[defaults setObject:currentVersion forKey:LAST_RUN_VERSION_KEY];?
return YES; ?} ?
return NO; ?
}??
6负溪,設(shè)置按鈕點擊一瞬間變色或變背景圖片透揣,常態(tài)下是另一種顏色或背景圖片,只需設(shè)置按鈕平時狀態(tài)和高亮狀態(tài)下的顏色和圖片即可川抡。
7辐真。KVC與KVO的用法總結(jié)?
?1,簡單的KVC(一個對象,在.h文件中聲明一個屬性名崖堤,)
? 最基本的操作屬性的兩個方法:?
?1侍咱, setValue:屬性值forKey:屬性名? 為指定屬性設(shè)置值 ? ?
?2,valueForKey:屬性名? 獲取指定屬性的值例子:
? //實例化一個對象?
?testView *tt = [[testView alloc]init];??
?//@“name”就是testViews聲明的一個屬性名? 設(shè)定?
?? [tt setValue:@"xiaobai " forKey:@“name"];?
?//取值??
? NSString *nameStr = [tt valueForKey:@"name"];??
? NSLog(@"-------------------dsasdsad%@",nameStr);?
注意事項:為避免setValue 和? valueForKey在執(zhí)行方法過程中找不到對應(yīng)的屬性名稱密幔,重寫下面兩個方法
//避免使用KVC設(shè)置的時候(即 setValue方法)程序崩潰楔脯,重寫下面這個方法,拋出異常
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{?
?? NSLog(@"我沒有這個屬性%@",key);
}
//避免使用KVC讀取的時候(即valueForKey方法)程序崩潰胯甩,重寫下面這個方法昧廷,拋出異常
-(id)valueForUndefinedKey:(NSString *)key{?
?? NSLog(@"我沒有這個屬性%@",key);? ?
?return nil;
}
處理nil值
當調(diào)用KVC來設(shè)置對象的屬性時,如果屬性的類型是對象類型(NSString)偎箫,嘗試將屬性設(shè)置為nil木柬,是合法的,程序可以正常運行但是如果屬性的類型是基本類型(如int,float,double),嘗試將屬性設(shè)置為nil淹办,程序?qū)罎⒁l(fā)異常眉枕。當程序嘗試為某個屬性設(shè)置nil值時,如果該屬性并不接受nil值怜森,那么程序會執(zhí)行該對象的setNilValueForKey:方法齐遵。同樣可以重寫這個方法避免異常
-(void)setNilValueForKey:(NSString *)key{? ??
int price;?
?? if ([key isEqualToString:@"price"]) {? ?
?? ? price = 0;?
?? }else? ? {??
? ? ? [super setNilValueForKey:key];? ??
}}
KVC對集合的操作
例如可以獲取數(shù)組中的一個最大值
NSArray *a = @[@4,@54,@2];
NSLog(@"max = %@",[a valueForKeyPath:@"@max.self"]);
KVO的操作
{self.person=[[Person alloc] init];??
? self.person.name=@"xiaowang";? ?
?//創(chuàng)建觀察者監(jiān)聽person的name。只要name值改變就會收到消息??
? /*? ? 1,誰是觀察者??
? 2塔插,路徑字符串,屬性字符串寫出來? ?
?3拓哟,收到通知后對哪些信息感興趣想许,這里寫對新值和舊值都感興趣。? ?
?4.可以傳遞一些其他信息,不傳遞寫nil即可流纹。? ? */
? ? [self.person addObserver:self forKeyPath:@"name" options: NSKeyValueObservingOptionNew |? ? NSKeyValueObservingOptionOld context:nil];? ??
? ? //當值改變的時候就會觸發(fā)KVO? ?
?/*? ? 通過點語法(setter)來修改屬性會觸發(fā)KVO糜烹,但是通過直接使用成員變量了修改屬性,不會觸發(fā)KVO? ? 通過KVO來修改屬性值會觸發(fā)KVO? ? */??
? self.person.name=@"xiaohuang";??
?// [self.person change];? ? ??
? //[self.person setValue:@"xiaofen" forKey:@“name"];}
//監(jiān)聽屬性name值一旦改變就會調(diào)用這個方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context
{
if ([keyPath isEqualToString:@"name"] && object == self.person) {
NSString *newname=change[@"new"];
NSString *oldname=change[@"old"];
NSLog(@"%@",oldname);
NSLog(@"%@",newname);
NSLog(@"%@",change);
}
}
8,打印oc中的CGPoint ,CGSize ,CGRect
NSLog(@"point: %@", NSStringFromCGPoint(point));
NSLog(@"size: %@", NSStringFromCGSize(size));
NSLog(@"rect: %@", NSStringFromCGRect(rect));
9,設(shè)置navigationbar的標題和返回按鈕
self.view.backgroundColor = [UIColor colorWithRed:0xf2/255.0 green:0xf3/255.0 blue:0xf8/255.0 alpha:1];
self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:89/255.0 green:107/255.0 blue:159/255.0 alpha:1];
self.navigationItem.title = @"我的課程";
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
UIBarButtonItem *btn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back_btn"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
self.navigationItem.leftBarButtonItem = btn;
10.創(chuàng)建tableview時候下面出現(xiàn)多余cell
添加如下代碼:
self.tableView.tableFooterView=[[UIView alloc]init];//關(guān)鍵語句
11漱凝,關(guān)于日期的操作
a,獲取n天后日期
-(NSString *)getNDay:(NSInteger)n{
NSDate*nowDate = [NSDate date];
NSDate* theDate;
if(n!=0){
NSTimeInterval? oneDay = 24*60*60*1;? //1天的長度
theDate = [nowDate initWithTimeIntervalSinceNow: oneDay*n ];//initWithTimeIntervalSinceNow是從現(xiàn)在往前后推的秒數(shù)
}else{
theDate = nowDate;
}
NSDateFormatter *date_formatter = [[NSDateFormatter alloc] init];
[date_formatter setDateFormat:@"MM月dd日"];
NSString *the_date_str = [date_formatter stringFromDate:theDate];
return the_date_str;
}
b疮蹦,獲取當天日期返回字符串
-(NSString *)getDate:(NSDate *)date
{
NSDateFormatter *format1=[[NSDateFormatter alloc]init];
[format1 setDateFormat:@"MM月dd日"];
NSString *str1=[format1 stringFromDate:date];
return str1;
}
c 傳入日期返回相對應(yīng)的周幾
-(NSString *)getweek:(NSDate *)date{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
//? ? NSDate *now;
NSDateComponents *comps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |
NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//? ? now=[NSDate date];
comps = [calendar components:unitFlags fromDate:date];
NSArray * arrWeek=[NSArray arrayWithObjects:@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六", nil];
NSString *str = [NSString stringWithFormat:@"%@",[arrWeek objectAtIndex:[comps weekday] - 1]];
return str;
}
d,獲取當前日期八天以后的日期
-(NSMutableArray *)latelyEightTime{
NSMutableArray *eightArr = [[NSMutableArray alloc] init];
for (int i = 0; i < 7; i ++) {
//從現(xiàn)在開始的24小時
NSTimeInterval secondsPerDay = i * 24*60*60;
NSDate *curDate = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"M月d日"];
NSString *dateStr = [dateFormatter stringFromDate:curDate];//幾月幾號
NSDateFormatter *weekFormatter = [[NSDateFormatter alloc] init];
//真機調(diào)試會出現(xiàn)問題 添加如下代碼:
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[weekFormatter setLocale:locale];
[weekFormatter setDateFormat:@"EEEE"];//星期幾 @"HH:mm 'on' EEEE MMMM d"];
NSString *weekStr = [weekFormatter stringFromDate:curDate];
//轉(zhuǎn)換英文為中文
NSString *chinaStr = [self cTransformFromE:weekStr];
//組合時間
NSString *strTime = [NSString stringWithFormat:@"%@ %@",dateStr,chinaStr];
[eightArr addObject:strTime];
}
return eightArr;
}
-(NSString *)cTransformFromE:(NSString *)theWeek{
NSString *chinaStr;
if(theWeek){
if([theWeek isEqualToString:@"Monday"]){
chinaStr = @"周一";
}else if([theWeek isEqualToString:@"Tuesday"]){
chinaStr = @"周二";
}else if([theWeek isEqualToString:@"Wednesday"]){
chinaStr = @"周三";
}else if([theWeek isEqualToString:@"Thursday"]){
chinaStr = @"周四";
}else if([theWeek isEqualToString:@"Friday"]){
chinaStr = @"周五";
}else if([theWeek isEqualToString:@"Saturday"]){
chinaStr = @"周六";
}else if([theWeek isEqualToString:@"Sunday"]){
chinaStr = @"周七";
}
}
return chinaStr;
}
12,為防止背景圖片變形茸炒,給button或label設(shè)置圖片時候愕乎,先獲取
UIimage *img = [uiimage imagenamed @“圖片名稱”];
設(shè)置背景色為圖片的空間的寬高為img.size.width和img.size.height;
即可保證圖片不會在控件中變形
13,設(shè)置點擊手勢時候壁公,注意要把添加的組件的
組件.userInteractionEnabled = YES感论;打開
14,tableview默認選中第一行
[self.table_view selectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
[self tableView:self.table_view didSelectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];//實現(xiàn)點擊第一行所調(diào)用的方法
15,對一個數(shù)判斷如果是整數(shù)則取整數(shù)紊册,如果有小數(shù)比肄,取小數(shù)后兩位
CGFloat money = [monLab floatValue] / 100;
float i=roundf(money);//對num取整
if (i==money) {
得到的數(shù)為:= [NSString stringWithFormat:@"%.0f",money];
}else{
得到的數(shù)為: = [NSString stringWithFormat:@"%.2f",money];
}
16.對不同的collectionview的item的布局
(除瀑布流之外)自動使得每行的item的寬度自動變化 ,調(diào)用collectionflowlayout的代理方法(遵守協(xié)議即可)囊陡,對不同的collectionview判斷每個item的字符串長度芳绩,要么一行顯示一個,要不一行顯示兩個
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize itemSize = CGSizeMake(100, 50);
NSString *itemStr;
if (collectionView == self.collectionView) {
itemStr = [self.Querymodel.list[indexPath.item] termName];
}
else if (collectionView == self.MincollectionView)
{
itemStr = self.qiciTime[indexPath.item];
}
else if (collectionView == self.classTimeTableV)
{
itemStr = [self.Querymodel.list[indexPath.item] lessonName];
}
CGRect rect = [itemStr boundingRectWithSize:CGSizeMake(MAXFLOAT, 25) options:1 attributes:@{NSFontAttributeName :[UIFont systemFontOfSize:13]} context:nil];(判斷每個字符串的長度方法)
if (rect.size.width > SCREEN_WIDTH/2 - 10) {
itemSize = CGSizeMake(SCREEN_WIDTH - 10 , 0.03748*SCREEN_HEIGHT);
}else
{
itemSize = CGSizeMake(SCREEN_WIDTH/2 - 20 , 0.03748*SCREEN_HEIGHT);
}
16 pickerview的使用方法和tableview的不同撞反,必須是先定一列妥色,然后確定每列的rows
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (component == 0) {
return [[self.stuEleModel.elementList[0] theoptions][row] parentName];
}else
{
return [[[self.stuEleModel.elementList[0] theoptions][_proIndex] childrenList] [row]childrenName];
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == 0) {
_proIndex = [pickerView selectedRowInComponent:0];
[_Stupick reloadComponent:1];
}
title1 = [[self.stuEleModel.elementList[0] theoptions][_proIndex] parentName];
NSInteger classIndex = [pickerView selectedRowInComponent:1];
title2 = [[[self.stuEleModel.elementList[0] theoptions][_proIndex] childrenList] [classIndex]childrenName];
_schoolClassB.text = [NSString stringWithFormat:@"%@-%@",title1,title2];
self.childrenId = [[self.stuEleModel.elementList[0] theoptions][_proIndex] parentId];
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component == 0) {
return [[self.stuEleModel.elementList[0] theoptions] count];
}
else{
return [[[self.stuEleModel.elementList[0] theoptions][_proIndex] childrenList] count];
}
}
17,label的屬性設(shè)置(行間距痢畜,兩邊對齊)
NSString *testString = [NSString stringWithFormat:@"%@",self.model.venue.theDescription];
NSMutableParagraphStyle *paragraphSty = [[NSMutableParagraphStyle alloc]init];
paragraphSty.alignment = NSTextAlignmentJustified;
[paragraphSty setLineSpacing:4];
NSMutableAttributedString *setString = [[NSMutableAttributedString alloc]initWithString:testString];
[setString addAttribute:NSParagraphStyleAttributeName value:paragraphSty range:NSMakeRange(0, [testString length])];
[contentL setAttributedText:setString];
18,撥打電話不會有停頓
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@“tel://%@“,self.model.venue.phone]];(有時tel在個別手機不適用垛膝,可用telprompt)
NSString *version = [UIDevice currentDevice].systemVersion;
if ([version intValue] < 10.0 ) {
[[UIApplication sharedApplication] openURL:url];
}else{
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
}];
}
19,計算 webView 顯示內(nèi)容后求出內(nèi)容的實際高度
鏈接: http://www.reibang.com/p/f3aa4852e7de (用的是連接中第二種方法)
_webView = [[UIWebView alloc]initWithFrame:(CGRectMake(0, CGRectGetMaxY(line3.frame),SCREEN_WIDTH, 100))];
_webView.delegate= self;
_webView.layer.borderColor = [UIColor clearColor].CGColor;
_webView.layer.borderWidth = 1;
NSString *str = [NSString
stringWithFormat:@“%@",self.model.venue.theDescription];
[_webView loadHTMLString:str baseURL:nil];
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
CGRect frame = webView.frame;
frame.size.width = SCREEN_WIDTH;
frame.size.height = 1;
webView.scrollView.scrollEnabled = NO;
webView.frame = frame;
frame.size.height = webView.scrollView.contentSize.height;
//? ? ? ? NSLog(@"frame = %@", [NSValue valueWithCGRect:frame]);
webView.frame = frame;
self.scrollView.contentSize = CGSizeMake(0, _lineHeight + frame.size.height);
});
}
20,一句話移除界面所有控件
[self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
21,判斷手機號碼是否正確
+ (NSString *)valiMobile:(NSString *)mobile{
if (mobile.length < 11)
{
return @"手機號長度只能是11位";
}else{
/**
* 移動號段正則表達式
*/
NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
/**
* 聯(lián)通號段正則表達式
*/
NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
/**
* 電信號段正則表達式
*/
NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
if (isMatch1 || isMatch2 || isMatch3) {
return nil;
}else{
return @"請輸入正確的電話號碼";
}
}
return nil;
}
22,判斷身份證號碼
鏈接:http://www.cnblogs.com/yswdarren/p/3559423.html
①根據(jù)百度百科中身份證號碼的標準實現(xiàn)該方法
②該方法只能判斷18位身份證,且不能判斷身份證號碼和姓名是否對應(yīng)(要看姓名和號碼是否對應(yīng),應(yīng)該有大量的數(shù)據(jù)庫做對比才能實現(xiàn))
③直接copy這段代碼,就能通過調(diào)用這個方法判斷身份證號碼是否符合標準,非常easy
/**
*? 驗證身份證號碼是否正確的方法
*
*? @param IDNumber 傳進身份證號碼字符串
*
*? @return 返回YES或NO表示該身份證號碼是否符合國家標準
*/
- (BOOL)isCorrect:(NSString *)IDNumber
{
NSMutableArray *IDArray = [NSMutableArray?array];
// 遍歷身份證字符串,存入數(shù)組中
for (int i =?0; i < 18; i++) {
NSRange range = NSMakeRange(i, 1);
NSString *subString = [IDNumber substringWithRange:range];
[IDArray addObject:subString];
}
// 系數(shù)數(shù)組
NSArray *coefficientArray = [NSArray?arrayWithObjects:@"7",?@"9", @"10",?@"5", @"8",?@"4", @"2",?@"1", @"6",?@"3", @"7",?@"9", @"10",?@"5", @"8",?@"4", @"2",?nil];
// 余數(shù)數(shù)組
NSArray *remainderArray = [NSArray?arrayWithObjects:@"1",?@"0", @"X",?@"9", @"8",?@"7", @"6",?@"5", @"4",?@"3", @"2",?nil];
// 每一位身份證號碼和對應(yīng)系數(shù)相乘之后相加所得的和
int sum = 0;
for (int i =?0; i < 17; i++) {
int coefficient = [coefficientArray[i]?intValue];
int ID = [IDArray[i] intValue];
sum += coefficient * ID;
}
// 這個和除以11的余數(shù)對應(yīng)的數(shù)
NSString *str = remainderArray[(sum % 11)];
// 身份證號碼最后一位
NSString *string = [IDNumber substringFromIndex:17];
// 如果這個數(shù)字和身份證最后一位相同,則符合國家標準,返回YES
if ([str isEqualToString:string]) {
return YES;
} else {
return NO;
}
}
23丁稀,將一個UIView顯示在最前面只需要調(diào)用其父視圖的 bringSubviewToFront()方法吼拥。
將一個UIView層推送到背后只需要調(diào)用其父視圖的 sendSubviewToBack()方法。
24线衫,當我們使用自動布局的時候為了不讓Contraint和view本身的autoresize屬性發(fā)生沖突凿可,我們首先需要把控件的屬性設(shè)置為 setTranslatesAutoresizingMaskIntoConstraints:NO
NSLayoutConstraint-代碼實現(xiàn)自動布局
例子:
[NSLayoutConstraint constraintWithItem:view1
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:view2
attribute:NSLayoutAttributeRight
multiplier:1
constant:10]
翻譯過來就是:view1的左側(cè),在授账,view2的右側(cè)枯跑,再多10個點,的地方白热。
25敛助,xcode8.1以后調(diào)用相冊需要在info.plist中添加字段Privacy - Privacy - Photo Library Usage Description 和 Privacy - Camera Usage Description
26,條形碼和二維碼的生成
a,條形碼:
- (void)viewDidLoad {
//原生條形碼
_barCodeImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 100, 300, 128)];
_barCodeImageView.center=CGPointMake(ScreenWidth/2.0, 100+64);
[self.view addSubview:_barCodeImageView];
_barCodeImageView.image=[self generateBarCode:@"1234948958096" width:self.barCodeImageView.frame.size.width height:self.barCodeImageView.frame.size.height];
}
-(UIImage*)generateBarCode:(NSString*)barCodeStr width:(CGFloat)width height:(CGFloat)height
{
// 生成二維碼圖片
CIImage *barcodeImage;
NSData *data = [barCodeStr dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:false];
CIFilter *filter = [CIFilter filterWithName:@"CICode128BarcodeGenerator"];
[filter setValue:data forKey:@"inputMessage"];
barcodeImage = [filter outputImage];
// 消除模糊
CGFloat scaleX = width / barcodeImage.extent.size.width; // extent 返回圖片的frame
CGFloat scaleY = height / barcodeImage.extent.size.height;
CIImage *transformedImage = [barcodeImage imageByApplyingTransform:CGAffineTransformScale(CGAffineTransformIdentity, scaleX, scaleY)];
return [UIImage imageWithCIImage:transformedImage];
}
b,二維碼:
二維碼生成步驟:
1.導入CoreImage框架
2.通過濾鏡CIFilter生成二維碼
示例代碼:
1.創(chuàng)建過濾器
CIFilter*filter = [CIFilterfilterWithName:@"CIQRCodeGenerator"];
2.恢復默認
[filtersetDefaults];
3.給過濾器添加數(shù)據(jù)(正則表達式/賬號和密碼)
NSString*dataString =@"http://www.520it.com";
NSData*data = [dataStringdataUsingEncoding:NSUTF8StringEncoding];
[filtersetValue:dataforKeyPath:@"inputMessage"];
4.獲取輸出的二維碼
CIImage*outputImage = [filteroutputImage];
5.顯示二維碼
self.imageView.image= [selfcreateNonInterpolatedUIImageFormCIImage:outputImagewithSize:200];
在第五步顯示二維碼的時候用了一個自己封裝的方法(解決二維碼圖片不清晰)
具體方法如下:
*根據(jù)CIImage生成指定大小的UIImage
*
*? @param image CIImage
*? @param size圖片寬度
- (UIImage*)createNonInterpolatedUIImageFormCIImage:(CIImage*)image withSize:(CGFloat) size
{
CGRectextent =CGRectIntegral(image.extent);
CGFloatscale =MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
// 1.創(chuàng)建bitmap;
size_twidth =CGRectGetWidth(extent) * scale;
size_theight =CGRectGetHeight(extent) * scale;
CGColorSpaceRefcs =CGColorSpaceCreateDeviceGray();
CGContextRefbitmapRef =CGBitmapContextCreate(nil, width, height,8,0, cs, (CGBitmapInfo)kCGImageAlphaNone);
CIContext*context = [CIContextcontextWithOptions:nil];
CGImageRefbitmapImage = [contextcreateCGImage:imagefromRect:extent];
CGContextSetInterpolationQuality(bitmapRef,kCGInterpolationNone);
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, extent, bitmapImage);
// 2.保存bitmap到圖片
CGImageRefscaledImage =CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return[UIImageimageWithCGImage:scaledImage];
}
27屋确,通過向storyboard上面的頁面進行傳值
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"goto"])
{
NSIndexPath *indexPath=self.tableView.indexPathsForSelectedRows[0];
secondLastViewController *last=segue.destinationViewController;
VCOneItemOfItemsModel *one=_dataSource[indexPath.row];
last.url=one.url;
}
}
28纳击,整個頁面放棄編輯的方法
[self.view endEditing:YES];
29,在tableview中為實現(xiàn)viewForHeaderInSection方法续扔,必須實現(xiàn)heightForHeaderInSection這個方法。
30,當tableview style設(shè)置為ground時焕数,每個section的header會跟隨tableview一起上下滑動纱昧;當style設(shè)置為plain時,每個section的header會懸浮在屏幕最上面堡赔,直到下一個section的header劃過來识脆,把當前的替換掉。但是當樣式為group是善已,需要重寫heightForHeaderInSection并且設(shè)置heightForFooterInSection:這個高度為0.1灼捂,這個協(xié)議方法,才會讓組頭視圖顯示出來,隨著屏幕上下滑動雕拼。
31,可變數(shù)組使用addobject方法時:可以字節(jié)添加一個對象如@“axsa”纵东,但是不能直接添加一個聲明的變量,需要轉(zhuǎn)換為NsNumber類型或NsString類型等其他類型進行存儲啥寇。
32,自定義cell和自定義view需要實現(xiàn)的方法
a:自定義view在
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{ 寫要添加的view
注意:不能像自定義cell中那里一樣使用self.frame.size.height等屬性偎球,會報錯。還是以屏幕的寬度和高度作參照辑甜。
}
}
方法中實現(xiàn)即可衰絮。
b:自定義tableviewcell在
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {? ? 僅需實例化要添加的組件 ,具體布局在下面方法中實現(xiàn)? }
}
-(void)layoutSubviews? //在該方法中實現(xiàn)cell里面組件的布局
{
[super layoutSubviews];//注意要先實現(xiàn)父視圖的方法
}
33,事件響應(yīng)的順序:
//將事件傳遞給下一個響應(yīng)者磷醋,讓下一個響應(yīng)者處理
[super touchesBegan:touches withEvent:event];
34,(tableview有時候頭部會出現(xiàn)莫名的空白添加如下代碼):
只要是滾動視圖或者滾動視圖的自子類猫牡,放到導航控制中,內(nèi)容會自動向下偏移64邓线,如果想取消這個偏移
self.automaticallyAdjustsScrollViewInsets=NO;
35,創(chuàng)建tabbar的時候添加子控制器
//創(chuàng)建控制器
NSString *viewControllerName = [NSString stringWithFormat:@"LZBViewController%d", i + 1];
Class cls = NSClassFromString(viewControllerName);
LZBBaseViewController *bvc = [[cls alloc] init];
bvc.tabBarItem = item;
//將控制器數(shù)組給分欄控制器管理
self.viewControllers = viewControllersArray;
36,CollectionView有關(guān)注意
a:創(chuàng)建collectionview的時候淌友,需要提前創(chuàng)建layout布局,代碼為:
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
而不是UICollectionViewLayout? !!!!!
b:對于再給collectionview設(shè)置layout時候的兩個如下屬性:
layout.minimumLineSpacing
layout.minimumInteritemSpacing
系統(tǒng)默認情況下上下滾動時骇陈,此時minimumLineSpacing代表每行的行間距震庭,minimumInteritemSpacing代表每列的列間距
如果修改滾動方向為水平滾動時,兩個屬性代表意義恰好相反:此時minimumLineSpacing代表每列的列間距你雌,minimumInteritemSpacing代表每行的行間距
37,a:當把navigationbar隱藏的時候器联,滾動視圖會留下空白的Top,(所有內(nèi)容向下偏移20px)婿崭,此時加:
self.automaticallyAdjustsScrollViewInsets = NO;//????自動滾動調(diào)整拨拓,默認為YES
b:在storyboard或xib上面設(shè)置navigationBar的顏色時,設(shè)置的顏色會和代碼設(shè)置的顏色有色差氓栈,是因為ios7以上的默認navigationBar是半透明的渣磷,所以顏色會有差異,此時添加:
self.navigationController.navigationBar.translucent = NO;//????Bar的模糊效果授瘦,默認為YES
此時的整個視圖的view會繼續(xù)往下偏移醋界,加代碼:
self.edgesForExtendedLayout = UIRectEdgeNone;//??? iOS7及以后的版本支持祟身,self.view.frame.origin.y會下移64像素至navigationBar下方
38,label的高度自適應(yīng)最簡單的兩句話
[lab.numberOfLines = 0];
[lab sizeToFit];
39,_weak和_unsafe_unretauned
1>都不是強指針(不是強引用),不能保住對象的命
2>_weak:所指向的對象銷毀后物独,會自動變成nil指針(空指針),不再指向已經(jīng)銷毀的對象
3>_unsafe_unretauned:所指向的對象銷毀后氯葬,指針仍指向已經(jīng)銷毀的對象.
40,使用cocoapods創(chuàng)建文件挡篓,創(chuàng)建podfile文件,想要創(chuàng)建那種可執(zhí)行exec的黑色文件帚称,創(chuàng)建完成在終端輸入 chmod 700 文件名 官研,想要恢復空白白色那種podfile文件,使用chmod 644 文件名闯睹。
41,用cocoapods創(chuàng)建項目流程(前提安裝cocoapods)
1戏羽,打開終端,輸入 cd + 空格 然后將項目根目錄拖拽到終端上面 然后回車 ?輸入touch Podfile 創(chuàng)建Podfile文件 返回項目文件夾打開Podfile文件 輸入platform :ios保存退出楼吃。返回終端
例如:
platform :ios, '8.0'
use_frameworks!
target '項目名稱' do
pod 'AFNetworking', '~>2.0'
pod 'MBProgressHUD','~>0.7'
pod 'SVPullToRefresh'
platform :ios,'6.0'
pod 'MJRefresh','~>2.4.7'
pod 'SDWebImage','~>3.7.3'
pod 'JSONModel','~>1.1.0'
pod 'NSData+MD5Digest', '~> 1.0.0'
pod 'Base64', '~> 1.0.1'
pod 'Masonry', '~> 0.6.3'
end,
2,回車始花,輸入? pod+空格+install? 然后回車,等待安裝,安裝完成點擊項目
42,終端修改文件(vim常用命令)
鏈接:http://www.cnblogs.com/softwaretesting/archive/2011/07/12/2104435.html
1孩锡,打開單個文件
vim file
2酷宵,正常模式(按Esc或Ctrl+[進入) 左下角顯示文件名或為空
插入模式(按i鍵進入) 左下角顯示—INSERT--
3,:wq 保存并退出