iOS開發(fā)小技巧

  • [去掉和修改UISearchBar 默認(rèn)的背景色(灰色)和TextField顏色](#去掉和修改UISearchBar 默認(rèn)的背景色(灰色)和TextField顏色)
  • 更改TextField的背景顏色
  • 如何正確的寫TODO惨险,F(xiàn)IXME
    1. 去掉和修改UISearchBar 默認(rèn)的背景色(灰色)和TextField顏色。
      測(cè)試環(huán)境:Xcode7, iOS9.2;
      默認(rèn)背景色:


      UISearchBar 默認(rèn)背景色(灰色)
  • 如何取消或修改默認(rèn)的灰色背景呢漱病?一行代碼可以搞定:
// !備注:當(dāng)添加scopeButtons時(shí),以下方法無(wú)效
for (UIView *view in self.searchBar.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
            [[view.subviews objectAtIndex:0] removeFromSuperview];
            break;
        }
}
//  添加以下代碼, 將UISearchBar背景顏色更改為藍(lán)色
//  self.searchBar.layer.backgroundColor = [UIColor blueColor].CGColor;  

完成后的效果如下圖:


UISearchBar 去掉背景色后的效果

<a href="changeTextFieldBgColor">更改TextField的背景顏色</a>

//第一種方法,設(shè)置背景圖片, 下面的方法支持iOS5.0
  [self.searchBa setSearchFieldBackgroundImage:[UIImage imageNamed:@"image"]  forState:UIControlStateNormal];

  //第二種方法,獲取SearchBar內(nèi)部的TextField,更改其顏色,不用額外增加圖片
    UITextField *textField = [self.searchBa valueForKey:@"_searchField"];
    textField.backgroundColor = [UIColor clearColor];

<a name="rendering-pane"></a>The Rendering Preference Pane

This is where I keep preferences relating to how I render and style the parsed markdown in the preview window.

3. 取消導(dǎo)航返回鍵的title:

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];

4. CocoaPods install CorePlot

測(cè)試環(huán)境: Xcode7, Simulator, iPhone6
雖然CorePlot的主頁(yè)上沒(méi)有顯示如何用CocoaPods安裝CorePlot, 但我們?nèi)匀豢梢杂肅ocoaPods安裝CorePlot

    pod 'CorePlot', '~> 2.0'

在項(xiàng)目中導(dǎo)入CorePlot:

#import <CorePlot/ios/CorePlot.h>

5. 如何統(tǒng)計(jì)項(xiàng)目中代碼的數(shù)量

 在終端中進(jìn)入項(xiàng)目所在文件夾洗鸵,輸入以下命令即可得到代碼總行數(shù)(包括注釋的代碼哦)
 find . -name "*.m" -or -name "*.h" | xargs grep -v "^$"| wc -l

6. UITabBarController+UINavigaitonController配合使用時(shí),各種情況下,如何設(shè)置tabBarItem.title和navigaitionController的title??? 每次都好煩,這次一次性搞定

  //在TabBarController的實(shí)現(xiàn)文件中實(shí)現(xiàn)以下方法
/**
 **  添加帶有導(dǎo)航控制器的childViewController
 **
 **  @param viewController 將要添加的ViewController, 將為其增加導(dǎo)航控制器
 **  @param show           是否顯示導(dǎo)航控制器頂部的title
 **  @param same           如果show=YES,導(dǎo)航控制器頂部的title是否與tabbarItem的title一致
 **  @param title          導(dǎo)航控制器的title
 **  @param barItemTitle   UITabBarItem的title
 **  @param image          UITabBarItem的image
 **  @param selectedImage  UITabbarItem的selectedImage
 **/
 - (void)addChildViewControlle:(nonnull UIViewController *)viewController showTitle:(BOOL)show same:(BOOL)same title:(nullable NSString *)title barItemTitle:(nonnull NSString *)barItemTitle image:(nonnull UIImage *)image selectedImage:(nonnull UIImage *)selectedImage{
    if (show && (title == nil || [title isEqualToString:@""])) {
        [NSException raise:@"TabBarController set excepition" format:@"The navigaitoncontroller's title cannot be nil because of you choosing show title"];
        return;
    }
    viewController.tabBarItem.image = image;
    viewController.tabBarItem.selectedImage = selectedImage;
    SDRootNavigationController *nav =[[SDRootNavigationController alloc] initWithRootViewController:viewController];
    if (show) {
        if (same) {
            viewController.title = barItemTitle;
        }else{
            viewController.title = title;
            nav.tabBarItem.title = barItemTitle; //如果同時(shí)設(shè)置兩個(gè)title,必須先實(shí)現(xiàn)導(dǎo)航欄的title,再實(shí)現(xiàn)tabbar的title
        }
    }else{
        nav.tabBarItem.title = barItemTitle;
    }
    
    [self addChildViewController:nav];
}
效果圖

7. Xcode目錄自動(dòng)同步

iOS開發(fā)都知道卷中,當(dāng)我們?cè)赬code中新建一個(gè)Group的時(shí)候,并沒(méi)有在finder中建立同步的Directory,當(dāng)我們?cè)趂inder中查找文件的時(shí)候塘秦,確實(shí)是一個(gè)大的麻煩,那么有解決的辦法嗎动看?答案是YES尊剔!
Synx
A command-line tool that reorganizes your Xcode project folder to match your Xcode groups.

Github主頁(yè)詳細(xì)介紹了用法,真的很強(qiáng)大菱皆。但是在實(shí)際使用過(guò)程中可能出現(xiàn)以下的問(wèn)題:

 //當(dāng)執(zhí)行g(shù)em install synx命令時(shí),可能出現(xiàn)以下的error
ERROR:  While executing gem ... (Gem::FilePermissionError)
You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.

http://stackoverflow.com/questions/14607193/installing-gem-or-updating-rubygems-fails-with-permissions-error
我的辦法是使用root權(quán)限

sudo -s  //獲取root權(quán)限
gem install synx //安裝aynx,如果在root權(quán)限下進(jìn)行此命令會(huì)報(bào)錯(cuò)
error : You cannot run Synx as root.
//切換回普通用戶须误,執(zhí)行同步命令
synx test.xocdeproj
//這樣X(jué)code目錄就會(huì)和Finder目錄一致了

感謝葉孤城葉大的提點(diǎn)。??

8. ARC下打印對(duì)象的引用計(jì)數(shù)

    id obj = [[NSObject alloc]init];
    NSLog(@"retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(obj)));
//output : retain count = 2

9. 如何更改TabBar上面的橫線

  - (UIImage *)contentImageWithColor:(UIColor *)color rect:(CGRect)rect{
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef contenxt = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(contenxt, color.CGColor);
    CGContextFillRect(contenxt, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
//設(shè)置陰影照片仇轻,也就是那條橫線霹期,就是那個(gè)高度為0.5的UIImageView
    [self.tabBar setShadowImage:[self contentImageWithColor:RGBCOLOR(247, 248, 247) rect:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)]];
//設(shè)置的時(shí)候,必須同時(shí)設(shè)置bacjgroudImage, 否則無(wú)效拯田。
    [self.tabBar setBackgroundImage:[self contentImageWithColor:RGBCOLOR(247, 248, 247) rect:CGRectMake(0, 0, SCREEN_WIDTH, 49)]];

10. Xcode添加代碼塊, 快捷開發(fā), 再也不用重復(fù)的寫Property了

/** <#summary#> */
@property (nonatomic,strong) <#type#> *<#name#>;

真相1

真相2

11. delloc中應(yīng)該寫什么历造?

(1). 如果當(dāng)前界面有NSTimer, 當(dāng)該界面出棧時(shí),應(yīng)該將定時(shí)器的取消和置空這樣處理

    - (void)viewDidDisappear:(BOOL)animated{
         [super viewDidDisappear:animated];
         [_myTimer invalidate];
          _myTimer = nil;
      }

而不是放在delloc中,否則內(nèi)存得不到釋放
(2). ARC中dealloc中不得顯式調(diào)用[super dealloc]
(3). [NSNotificationCenter defaultCenter] removeObserver 操作應(yīng)該放在delloc中船庇,而不是ViewDisapper中

//官網(wǎng)解釋
The following example illustrates how to unregister someObserver for all notifications for which it had previously registered. This is safe to do in the dealloc method, but should not otherwise be used—use removeObserver:name:object: instead.

12. 如何獲取APP的名稱吭产?

//獲取appName-info.plist中app的名稱(適用于只有一個(gè)名字的情況)
[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]
//獲取InfoPlist.strings中的app名稱(適用于有中英文或者多個(gè)Target的情況)
[[[NSBundle mainBundle] localizedInfoDictionary] objectForKey:@"CFBundleDisplayName"]

13. Mac顯示和隱藏文件夾

在終端(Terminal)輸入如下命令,即可顯示隱藏文件和文件夾

defaults write com.apple.finder AppleShowAllFiles -boolean true ; killall Finder

如需再次隱藏原本隱藏的文件和文件夾鸭轮,可以輸入如下命令

defaults write com.apple.finder AppleShowAllFiles -boolean false ; killall Finder

14. 消除‘performSelector may cause a leak because its selector is unkonwn'

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
      [self performSelector:selector withObject:info];
#pragma clang diagnostic pop

15: 獲取設(shè)備內(nèi)所有已安裝APP的信息(訪問(wèn)私有方法汇跨,上架可能被拒)

    Class c =NSClassFromString(@"LSApplicationWorkspace");
    id s = [(id)c performSelector:NSSelectorFromString(@"defaultWorkspace")];
    NSArray *array = [s performSelector:NSSelectorFromString(@"allInstalledApplications")];
    for (id item in array){
        NSLog(@"%@",[item performSelector:NSSelectorFromString(@"applicationIdentifier")]);
        //NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleIdentifier")]);
        NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleVersion")]);
        NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]);
    }
    

16:獲取系統(tǒng)版本號(hào)的正確方式

   [NSProcessInfo processInfo].operatingSystemVersion
    NSInteger major = [NSProcessInfo processInfo].operatingSystemVersion.majorVersion;
    NSInteger minor = [NSProcessInfo processInfo].operatingSystemVersion.minorVersion;
    NSInteger patch = [NSProcessInfo processInfo].operatingSystemVersion.patchVersion;

17:一個(gè)全局的數(shù)組

static NSString const *presendientOfUsa[4] = {
    @"Obama",
    @"Trump",
    @"Bush",
    @"Washington"
};
static NSString const *imgArr[3] = {
    @"引導(dǎo)頁(yè)1",
    @"引導(dǎo)頁(yè)2",
    @"引導(dǎo)頁(yè)3"
};
除了NSString類型之外,都不允許在方法外部聲明一個(gè)‘靜態(tài)全局常量類型的OC對(duì)象’沧奴。
你聲明的static const NSArray * presendientOfUsa 在‘編譯’的時(shí)候系統(tǒng)并不知道imgArr是什么類型奕污,PS:全局常量類型的常量,static const是系統(tǒng)在編譯的時(shí)候就需要確定你所定義的常量是什么類型的按厘,然而OC的對(duì)象的類型是在‘運(yùn)行時(shí)’確定的医吊。與基本數(shù)據(jù)類型的確定時(shí)間不同,由編譯的時(shí)候推到了運(yùn)行時(shí)(OC支持多態(tài)的原因)逮京。
但是NSString除外卿堂,NSString是一種特殊的數(shù)據(jù)類型,有特殊的存儲(chǔ)結(jié)構(gòu)和權(quán)限來(lái)保證系統(tǒng)能夠識(shí)別。

18: 如何正確的寫TODO草描,F(xiàn)IXME

開發(fā)中有一些工作是需要我們稍后完成的览绿,我們用TODO標(biāo)記;有一些暫時(shí)處理不了的bug穗慕,用FIXME標(biāo)記饿敲,后續(xù)處理,一般是這樣


TODO逛绵,F(xiàn)IXME

有一個(gè)潛在的問(wèn)題是:如果我們忘了诀蓉?或者同事不知道這些標(biāo)記,可能會(huì)出現(xiàn)遺留問(wèn)題暑脆。我們希望在程序運(yùn)行的時(shí)候渠啤,能夠清除的看到,一般在Issue navigator上添吗。
那我們?cè)黾右粋€(gè)腳本沥曹,在程序運(yùn)行時(shí),自動(dòng)檢測(cè)出這些信息碟联,并增加在Issue navigator上

TAGS="TODO:|FIXME:"
echo "searching ${SRCROOT} for ${TAGS}"
find "${SRCROOT}" \( -name "*.m" \) -print0 | xargs -0 egrep --with-filename --line-number --only-matching "($TAGS).*\$" | perl -p -e "s/($TAGS)/ warning: \$1/"
添加過(guò)程
運(yùn)行后的效果

19: Weak and Strong

#define WeakSelf(type) __weak typeof(type) weak##type = type; //weak
#define StrongSelf(type) __strong typeof(type) type = weak##type; //strong

20: UIScrollView(UITableVIew and UICollectionView) 滑動(dòng)到頂部

 ??   [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
 ?   [self.tableView setContentOffset:CGPointZero animated:YES];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末妓美,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子鲤孵,更是在濱河造成了極大的恐慌壶栋,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,270評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件普监,死亡現(xiàn)場(chǎng)離奇詭異贵试,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)凯正,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門毙玻,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人廊散,你說(shuō)我怎么就攤上這事桑滩。” “怎么了允睹?”我有些...
    開封第一講書人閱讀 165,630評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵运准,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我缭受,道長(zhǎng)胁澳,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,906評(píng)論 1 295
  • 正文 為了忘掉前任贯涎,我火速辦了婚禮听哭,結(jié)果婚禮上慢洋,老公的妹妹穿的比我還像新娘塘雳。我一直安慰自己陆盘,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,928評(píng)論 6 392
  • 文/花漫 我一把揭開白布败明。 她就那樣靜靜地躺著隘马,像睡著了一般。 火紅的嫁衣襯著肌膚如雪妻顶。 梳的紋絲不亂的頭發(fā)上酸员,一...
    開封第一講書人閱讀 51,718評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音讳嘱,去河邊找鬼幔嗦。 笑死,一個(gè)胖子當(dāng)著我的面吹牛沥潭,可吹牛的內(nèi)容都是我干的邀泉。 我是一名探鬼主播,決...
    沈念sama閱讀 40,442評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼钝鸽,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼汇恤!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起拔恰,我...
    開封第一講書人閱讀 39,345評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤因谎,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后颜懊,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體财岔,經(jīng)...
    沈念sama閱讀 45,802評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,984評(píng)論 3 337
  • 正文 我和宋清朗相戀三年河爹,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了使鹅。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,117評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡昌抠,死狀恐怖患朱,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情炊苫,我是刑警寧澤裁厅,帶...
    沈念sama閱讀 35,810評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站侨艾,受9級(jí)特大地震影響执虹,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜唠梨,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,462評(píng)論 3 331
  • 文/蒙蒙 一袋励、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦茬故、人聲如沸盖灸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)赁炎。三九已至,卻和暖如春钾腺,著一層夾襖步出監(jiān)牢的瞬間徙垫,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工放棒, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留姻报,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,377評(píng)論 3 373
  • 正文 我出身青樓间螟,卻偏偏與公主長(zhǎng)得像逗抑,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子寒亥,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,060評(píng)論 2 355

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