iOS開發(fā)常用代碼匯總

1.UITableView****點擊段頭收齊放下咧织、****cell****側(cè)滑刪除****Demo —> /****Work / text1Demo**

2.****改變****UITextField****的****placeholder字體的顏色

{
    textField.placeholder = @"username is in here!";
    [textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
    [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placehold'];
}

3.lable里的字體設(shè)置不同顏色和字體大小

{
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed String扼劈,try your best to test attributed string text"];
[str addAttribute:NSForegroundColorAttributeName
value:[UIColor blueColor]
range:NSMakeRange(0,5)];
[str addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(6,12)];
[str addAttribute:NSForegroundColorAttributeName
value:[UIColor greenColor]
range:NSMakeRange(19,6)];
[str addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"Arial" size:30.0]
range:NSMakeRange(0, 5)];
[str addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"Arial" size:30.0]
range:NSMakeRange(6, 12)];
[str addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"Arial" size:30.0]
range:NSMakeRange(19, 6)];
UILabel *attrLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 150, 320 - 40, 90)];
attrLabel.attributedText = str;
attrLabel.numberOfLines = 0;
}

iOS UIFont字體名字大全(http://blog.sina.com.cn/s/blog_6c9d5da50101fujl.html)

4. Masonry的使用(http://www.cocoachina.com/ios/20141219/10702.html)**

Masonry支持哪一些屬性

@property (nonatomic, strong, readonly) MASConstraint *left;
@property (nonatomic, strong, readonly) MASConstraint *top;
@property (nonatomic, strong, readonly) MASConstraint *right;
@property (nonatomic, strong, readonly) MASConstraint *bottom;
@property (nonatomic, strong, readonly) MASConstraint *leading;
@property (nonatomic, strong, readonly) MASConstraint *trailing;
@property (nonatomic, strong, readonly) MASConstraint *width;
@property (nonatomic, strong, readonly) MASConstraint *height;
@property (nonatomic, strong, readonly) MASConstraint *centerX;
@property (nonatomic, strong, readonly) MASConstraint *centerY;
@property (nonatomic, strong, readonly) MASConstraint *baseline;

這些屬性與NSLayoutAttrubute的對照表如下
其中l(wèi)eading與left trailing與right在正常情況下是等價的但是當(dāng)一些布局是從右至左時(比如阿拉伯文?沒有類似的經(jīng)驗)則會對調(diào)換句話說就是基本可以不理不用用left和right就好了
在Masonry中能夠添加autolayout約束有三個函數(shù)

- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block;
- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block;
- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block;

mas_makeConstraints只負(fù)責(zé)新增約束Autolayout不能同時存在兩條針對于同一對象的約束否則會報錯
mas_updateConstraints針對上面的情況會更新在block中出現(xiàn)的約束不會導(dǎo)致出現(xiàn)兩個相同約束的情況
mas_remakeConstraints則會清除之前的所有約束僅保留最新的約束
三種函數(shù)善加利用就可以應(yīng)對各種情況了

5.iOS****調(diào)用系統(tǒng)功能****http://www.reibang.com/p/78db0e46d954

6.****去掉****UItableview headerview黏性

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
   if (scrollView == _tableView) {
      CGFloat sectionHeaderHeight = 36;
      if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) {
          scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
      } else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
          scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
      }
   }
}

說明
sectionHeaderHeight的值要根據(jù)自己的而定
_tableView如果一個類里有多個表格缘挑,要明確指明要去掉哪一個表格頭的粘性


7.iOS****完整****App資源收集

http://www.henishuo.com/ios-app-fully-code/


8.****獲取文件大小****fileSize &&文件刪除

NSDictionary *fileAttributes = [[NSFileManager defaultManager] fileAttributesAtPath:path traverseLink:YES];
unsigned long long length = [fileAttributes fileSize];
float ff = length/1024.0/1024.0;
NSLog(@"length== %.2f",ff);
---------------------
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
//如果存在就刪除
[[NSFileManager defaultManager] removeItemAtPath: path error:nil];
}

9.獲取本機(jī)當(dāng)前語言

/**  *得到本機(jī)現(xiàn)在用的語言* en:英文zh-Hans:簡體中文zh-Hant:繁體中文ja:日本......  */
+ (NSString*)getPreferredLanguage {
NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];
NSLog(@"Preferred Language:%@", preferredLang);
**return **preferredLang;
}

10.圖片拉伸

//加載圖片
UIImage *image = [UIImage imageNamed:@"chat_send_nor"];
//設(shè)置端蓋的值
CGFloat top = image.size.height * 0.5;
CGFloat left = image.size.width * 0.5;
CGFloat bottom = image.size.height * 0.5;
CGFloat right = image.size.width * 0.5;
//設(shè)置端蓋的值
UIEdgeInsets edgeInsets = UIEdgeInsetsMake(top, left, bottom, right);
//設(shè)置拉伸的模式
UIImageResizingMode mode = UIImageResizingModeStretch;
//拉伸圖片
UIImage *newImage = [image resizableImageWithCapInsets:edgeInsets resizingMode:mode];
//設(shè)置按鈕的背景圖片
[btn setBackgroundImage:newImage forState:UIControlStateNormal];

####11.UIAlertView****的字體大小和顏色自定義**
- (IBAction)showBigAlert:(id)sender {
UIAlertView* find = [[UIAlertView alloc] initWithTitle:@"big size view" message:@"do you see it" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
//[find setDelegate:self];
/*
UIAlertView *find = [[UIAlertView alloc] initWithFrame:CGRectMake(5, 20, 320,700)];
find.title=@"big size view" ;
find.message=@"some message";
*/
[find show];
[find release];
}

//- (void)willPresentAlertView:(UIAlertView *)alertView
-(void)willPresentAlertView:(UIAlertView *)alertView {
[alertView setFrame:CGRectMake(1, 20, 1000, 600)];
for( UIView * view in alertView.subviews )
{
if( [view isKindOfClass:[UILabel class]] )
{
UILabel* label = (UILabel*) view;
label.textAlignment = UITextAlignmentLeft;
label.font=[UIFont fontWithName:@"STHeitiSC-Medium" size:18];
label.textColor=[UIColor greenColor];
}

if ( [view isKindOfClass:[UIButton class]] ){
}

12.UITextField中輸入文字或英文返回文本長度

- (void)textFieldDidBeginEditing:(UITextField *)textField{
          [textField addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
}

- (void)textFieldEditChanged:(UITextField *)textField{
   if (textField.text.length == 0) {
      [_sendButton setTitleColor:LIGHTGAYCOLOR forState:(UIControlStateNormal)];
_sendButton.userInteractionEnabled = NO; 
   }else{
      [_sendButton setTitleColor:SUBJECTCOLOR forState:(UIControlStateNormal)];
_sendButton.userInteractionEnabled = YES; 
   }
}

13.JSON的 “” 轉(zhuǎn)換為 nil

使用AFNetworking時盛撑,使用

AFJSONResponseSerializer *response = [[AFJSONResponseSerializer alloc] init];
response.removesKeysWithNullValues = YES;
_sharedClient.responseSerializer = response;

這個參數(shù)removesKeysWithNullValues可以將null的值刪除,那么就Value為nil了

14.忽略靜音開關(guān)

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

15.iOS中幾種定時器

CADisplayLink

1)創(chuàng)建方法

        self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
        [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

2)停止方法

         [self.displayLink invalidate];
         self.displayLink = nil;

當(dāng)把CADisplayLink對象add到runloop中后藻雪,selector就能被周期性調(diào)用仰坦,類似于重復(fù)的NSTimer被啟動了扣孟;執(zhí)行invalidate操作時,CADisplayLink對象就會從runloop中移除瞬雹,selector調(diào)用也隨即停止昧谊,類似于NSTimer的invalidate方法。

3)特性
屏幕刷新時調(diào)用

CADisplayLink是一個能讓我們以和屏幕刷新率同步的頻率將特定的內(nèi)容畫到屏幕上的定時器類酗捌。CADisplayLink以特定模式注冊到runloop后呢诬,每當(dāng)屏幕顯示內(nèi)容刷新結(jié)束的時候,runloop就會向CADisplayLink指定的target發(fā)送一次指定的selector消息胖缤,CADisplayLink類對應(yīng)的selector就會被調(diào)用一次尚镰。所以通常情況下,按照iOS設(shè)備屏幕的刷新率60次/秒

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末哪廓,一起剝皮案震驚了整個濱河市狗唉,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌涡真,老刑警劉巖分俯,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異综膀,居然都是意外死亡澳迫,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進(jìn)店門剧劝,熙熙樓的掌柜王于貴愁眉苦臉地迎上來橄登,“玉大人,你說我怎么就攤上這事讥此÷G拢” “怎么了?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵萄喳,是天一觀的道長卒稳。 經(jīng)常有香客問我,道長他巨,這世上最難降的妖魔是什么充坑? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任减江,我火速辦了婚禮,結(jié)果婚禮上捻爷,老公的妹妹穿的比我還像新娘辈灼。我一直安慰自己,他們只是感情好也榄,可當(dāng)我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布巡莹。 她就那樣靜靜地躺著,像睡著了一般甜紫。 火紅的嫁衣襯著肌膚如雪降宅。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天囚霸,我揣著相機(jī)與錄音腰根,去河邊找鬼。 笑死邮辽,一個胖子當(dāng)著我的面吹牛唠雕,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播吨述,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼岩睁,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了揣云?” 一聲冷哼從身側(cè)響起捕儒,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎邓夕,沒想到半個月后刘莹,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡焚刚,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年点弯,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片矿咕。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡抢肛,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出碳柱,到底是詐尸還是另有隱情捡絮,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布莲镣,位于F島的核電站福稳,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏瑞侮。R本人自食惡果不足惜的圆,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一鼓拧、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧略板,春花似錦毁枯、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽藐鹤。三九已至瓤檐,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間娱节,已是汗流浹背挠蛉。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留肄满,地道東北人谴古。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像稠歉,于是被迫代替她去往敵國和親掰担。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內(nèi)容