iOS 開發雜記

拋出異常

NSException* ex = [NSException exceptionWithName:@"name" reason:@"reason" userInfo:nil];
[ex raise];

UILabel文字添加刪除線

    NSAttributedString* attrStr =
        [[NSAttributedString alloc] initWithString:@"ddddd"
                                        attributes:
                                            @{ NSFontAttributeName : [UIFont systemFontOfSize:20.f],
                                                NSForegroundColorAttributeName : [UIColor redColor],
                                                NSStrikethroughStyleAttributeName : @(NSUnderlineStyleSingle | NSUnderlinePatternSolid),
                                                NSStrikethroughColorAttributeName : [UIColor blueColor] }];
    self.label.attributedText = [attrStr copy];

自定義控件的數據源設置

自定義控件應該自己定義相關的數據源,
然后其他數據源想要使用這個自定義控件,
就把自定義控件的模型放到數據源模型中,
然后通過setValue :forKey :來進行對自定義控件的模型賦值。

NSString

//去掉空格
NSString* _titleLabelOutSpace = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
//NSString ->NSInteger
[_titleLabelOutSpace integerValue];

NSArray

//NSString  NSArray  互轉
NSArray *arr = [@"a,b,c" componentsSeparatedByString:@","];


- (void)hasString:(NSString*)str1 string2:(NSString*)str2
{
    NSString* string1 = str1;
    NSString* string2 = str2;
    NSRange range = [string1 rangeOfString:string2];
    NSUInteger location = range.location;
    NSUInteger length = range.length;
    NSString* astring = [[NSString alloc] initWithString:[NSString stringWithFormat:@"Location:%zd,Leight:%zd", location, length]];
    NSLog(@"astring:%@", astring);
}
    [self hasString:@"1111111" string2:@"2"];
   //astring:Location:9223372036854775807, length:0
    [self hasString:@"11111112" string2:@"2"];
   //astring:Location:8,Leight:1
可以根據length來判斷是否有字段

數組排序

[self.HelpManager.PublishScopeList sortedArrayUsingComparator:^NSComparisonResult(PublishScopeListModel* obj1, PublishScopeListModel* obj2) {

        NSComparisonResult result = [obj1.num compare:obj2.num];
        return result == NSOrderedAscending; // 降序:NSOrderedAscending====升序:NSOrderedDescending
    }];

為UICollectionView添加頭視圖的兩種方式

  • 給UICollectionView添加:UICollectionElementKindSectionHeader
  • 設置UICollectionView的:contentInset
- (UICollectionReusableView*)collectionView:(UICollectionView*)collectionView viewForSupplementaryElementOfKind:(NSString*)kind atIndexPath:(NSIndexPath*)indexPath
{
    UICollectionReusableView* cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"_CollectionReusableViewIndetifier" forIndexPath:indexPath];
    return cell;
}
- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
{
    return CGSizeMake(ScreenWidth, 44);
}
    CGFloat _adH = 120.0;
    self.collectionView.contentInset = UIEdgeInsetsMake(_adH, 0, 0, 0);
    [self.adImgeView setFrame:CGRectMake(0, CGRectGetMinY(self.collectionView.frame) - _adH, CGRectGetWidth(self.collectionView.frame), _adH)];

TableViewCell創建技巧

#import <UIKit/UIKit.h>
static NSString* SEGPictorialDetailADCellIdentifier = @"SEGPictorialDetailADCellIdentifier";

static NSString* SEGHelpViewCellIdentifier = @"_SEGHelpViewCellIdentifier";  
static NSString* SEGHelpViewCellDetailTopIdentifier = @"_SEGHelpViewCellDetailTopIdentifier";  
static NSString* SEGHelpViewCellDetailDwonIdentifier = @"_SEGHelpViewCellDetailDwonIdentifier";   


@interface SEGPictorialDetailADCell : UITableViewCell
+ (instancetype)cellWithTableView:(UITableView*)tableView;
+ (instancetype)cellWithTableView:(UITableView*)tableView reuseIdentifier:(NSString*)reuseIdentifier;
@end

#import "SEGPictorialDetailADCell.h"

@implementation SEGPictorialDetailADCell

+ (instancetype)cellWithTableView:(UITableView*)tableView
{
    SEGPictorialDetailADCell* cell = [tableView dequeueReusableCellWithIdentifier:SEGPictorialDetailADCellIdentifier];

    if (cell == nil) {

        cell = [[SEGPictorialDetailADCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SEGPictorialDetailADCellIdentifier];
    }


    return cell;
}

+ (instancetype)cellWithTableView:(UITableView*)tableView reuseIdentifier:(NSString*)reuseIdentifier
{
    SEGHelpViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];

    if (cell == nil) {
        cell = [[SEGHelpViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }

    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString*)reuseIdentifier
{
    self.CellIdentifier = reuseIdentifier;//通過記錄不同的ID來布置對應的界面
    if (self == [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
    }

    return self;
}
@end

TableHeaderView動態改變高度

[self.tableView beginUpdates];
[self.tableView setTableHeaderView:self.webView];
[self.tableView endUpdates];

去掉多余的空白的cell

self.contactsTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

切割圖片

UIImage* Image = [UIImage imageNamed:@"RedButton"];
Image = [logBackgroundImage stretchableImageWithLeftCapWidth:logBackgroundImage.size.width * 0.5 topCapHeight:logBackgroundImage.size.height * 0.5];
[self.loginBtn setBackgroundImage:Image forState:UIControlStateNormal];

實現跳轉safari,phone或message

//調用 電話phone
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://10086"]];

//調用自帶 瀏覽器 safari
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.baidu.com"]];

//調用 自帶mail
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://sam@icloud.com"]];

//調用 SMS
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://111111"]];

//跳轉到系統設置相關界面
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];

程序中獲取軟件的版本號和app名稱

應用程序的名稱和版本號等信息都保存在mainBundle的infoDictionary字典中,用下面代碼可以取出來。  
NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];  
NSString* versionNum =[infoDict objectForKey:@"CFBundleVersion"];//版本名稱  
NSString*appName =[infoDict objectForKey:@"CFBundleDisplayName"];//app名稱 

在有uinavigation,uitoolbar的情況下,如何添加一個全屏的 uiview (作為顯示一個進度框,任何區域無法觸摸而使用)

[[UIApplication sharedApplication].keyWindow addSubview:waitingview]; 

在項目用代碼打開AppStore

NSString *url = [NSString stringWithFormat:@"http://itunes.apple.com/cn/app/huo-xing-she-xin-dian/id549425594?l=en&mt=8"];  
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

使屏幕一直保持喚醒狀態?(就是不自動黑屏)

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

隱藏UINavigationBar

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationControllersetNavigationBarHidden:YESanimated:YES]; //設置隱藏
    [super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self.navigationControllersetNavigationBarHidden:NOanimated:YES];//設置顯示
    [super viewWillDisappear:animated];
}

在navigationviewcontroller中,pop到指定的VC

NSArray *viewControllers=[self.navigationController viewControllers];  
UIViewController *controller=[viewControllers objectAtIndex:1];  //跳轉到第一個VC
[self.navigationController popToViewController:controller animated:YES];  

獲取手機硬件信息

[[UIDevice currentDevice] systemName];[[UIDevice currentDevice] systemVersion];
[[UIDevice currentDevice] uniqueIdentifier];
[[UIDevice currentDevice] model];
[[UIDevice currentDevice] name];

真機上結果:
System Name: iPhone OSSystem 
Version: 4.2.1
Unique ID: 9b5ded78d5fa0ac96250f8b4af0e46f40b96ea6d
Model: iPhone
Name: “wwk”的 iPhone

模擬器上結果:
System Name: iPhone OSSystem 
Version: 4.2
Unique ID: 21FFE0FF-429B-5D0B-96D2-EADCA3203260
Model: iPhone Simulator
Name: iPhone Simulator

URL編碼、解碼

// 1. URL編碼:ios中http請求遇到漢字的時候,需要轉化成UTF-8:
 NSString* urlString = @"http://www.baidu.com!name=小明";
NSString * encodingString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//結果:http://www.baidu.com!name=%E5%B0%8F%E6%98%8E

// 2.URL解碼:請求后,返回的數據,如何顯示的是這樣的格式:%3A%2F%2F,此時需要我們進行UTF-8解碼,用到的方法是:
NSString *str = [encodingString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

獲取URL中的細節

NSURL* url = [NSURL URLWithString:@"http://www.baidu.com/s?tn=baiduhome_pg&bs=NSRUL&f=8&rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709"];
    NSLog(@"Scheme: %@", [url scheme]);
    NSLog(@"Host: %@", [url host]);
    NSLog(@"Port: %@", [url port]);
    NSLog(@"Path: %@", [url path]);
    NSLog(@"Relative path: %@", [url relativePath]);
    NSLog(@"Path components as array: %@", [url pathComponents]);
    NSLog(@"Parameter string: %@", [url parameterString]);
    NSLog(@"Query: %@", [url query]);
    NSLog(@"Fragment: %@", [url fragment]);
    NSLog(@"User: %@", [url user]);
    NSLog(@"Password: %@", [url password]);

/*
2016-05-27 11:38:23.503 FourNews[2358:116708] Scheme: http
2016-05-27 11:38:23.504 FourNews[2358:116708] Host: www.baidu.com
2016-05-27 11:38:23.504 FourNews[2358:116708] Port: (null)
2016-05-27 11:38:23.504 FourNews[2358:116708] Path: /s
2016-05-27 11:38:23.504 FourNews[2358:116708] Relative path: /s
2016-05-27 11:38:23.504 FourNews[2358:116708] Path components as array: (
    "/",
    s
)
2016-05-27 11:38:23.504 FourNews[2358:116708] Parameter string: (null)
2016-05-27 11:38:23.505 FourNews[2358:116708] Query: tn=baiduhome_pg&bs=NSRUL&f=8&rsv_bp=1&rsv_spt=1&wd=NSurl&inputT=2709
2016-05-27 11:38:23.505 FourNews[2358:116708] Fragment: (null)
2016-05-27 11:38:23.505 FourNews[2358:116708] User: (null)
2016-05-27 11:38:23.505 FourNews[2358:116708] Password: (null)
*/

獲取URL中的參數

- (NSDictionary*)dictionaryFromQuery:(NSString*)query usingEncoding:(NSStringEncoding)encoding
{
    NSCharacterSet* delimiterSet = [NSCharacterSet characterSetWithCharactersInString:@"&;"];
    NSMutableDictionary* pairs = [NSMutableDictionary dictionary];
    NSScanner* scanner = [[NSScanner alloc] initWithString:query];
    while (![scanner isAtEnd]) {
        NSString* pairString = nil;
        [scanner scanUpToCharactersFromSet:delimiterSet intoString:&pairString];
        [scanner scanCharactersFromSet:delimiterSet intoString:NULL];
        NSArray* kvPair = [pairString componentsSeparatedByString:@"="];
        if (kvPair.count == 2) {
            NSString* key = [[kvPair objectAtIndex:0]
                stringByReplacingPercentEscapesUsingEncoding:encoding];
            NSString* value = [[kvPair objectAtIndex:1]
                stringByReplacingPercentEscapesUsingEncoding:encoding];
            [pairs setObject:value forKey:key];
        }
    }

    return [NSDictionary dictionaryWithDictionary:pairs];
}

[**ViewController respondsToSelector:]: message sent to deallocated instance崩潰問題解決方法

這是因為這個UIViewController釋放后,又再次向這個VC調用了某些請求導致的,一般出現這種報錯是UIViewController里面有設置xxx.delegate=self,這些代理有延時方法,例如等待網絡返回等
當導航欄直接返回時,UIViewController已經被銷毀,延時方法再調用此野指針VC,便會導致崩潰
解決方法:
1 在dealloc中設置xx.delegate = nil ,這個是程序沒有使用ARC才可以
2 在viewWillDisappear方法中把所有xxx.delegate=self的具有延時方法的delegate置nil,我的做法是不過有沒有延時方法,

UIView有關的雜技

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

推薦閱讀更多精彩內容

  • 下面的內容基本都是我親測的 Xcode目錄位置:~/Library/Developer/Xcode/ Code S...
    Mr_Zander閱讀 336評論 0 1
  • 因為記性不好,常常看到點東西,都感覺很好,但是經常時間一長都忘了,所以現在些雜記,記住這些。慢慢補充。 1.iOS...
    小小看護閱讀 127評論 0 0
  • 雜記: 1.安裝Xcode插件管理終端命令: curl -fsSL https://raw.githubuserc...
    suncorex閱讀 239評論 0 1
  • iOS類庫合集: http://www.code4app.com/thread-7831-1-1.htmliOS最...
    暮雨飛煙閱讀 151評論 0 0
  • 1,Search Bar 怎樣去掉背景的顏色(storyboard里只能設置background顏色,可是發現cl...
    以德扶人閱讀 2,406評論 2 50