<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>知识库 &#187; 代码片断</title>
	<atom:link href="http://www.wezu.net/blog/archives/category/%e4%bb%a3%e7%a0%81%e7%89%87%e6%96%ad/feed" rel="self" type="application/rss+xml" />
	<link>http://www.wezu.net/blog</link>
	<description>知识就是力量，知识就是财富！</description>
	<lastBuildDate>Sat, 22 Jan 2011 08:31:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>NSString</title>
		<link>http://www.wezu.net/blog/archives/86</link>
		<comments>http://www.wezu.net/blog/archives/86#comments</comments>
		<pubDate>Sat, 22 Jan 2011 08:26:29 +0000</pubDate>
		<dc:creator>snox</dc:creator>
				<category><![CDATA[代码片断]]></category>
		<category><![CDATA[ios dev]]></category>

		<guid isPermaLink="false">http://www.wezu.net/blog/?p=86</guid>
		<description><![CDATA[#include /* 说明 malloc, NULL, size_t */ #include /* 说明 va_ 相关类型和函数 */ #include /* 说明 strcat 等 */ char *vstrcat(const char *first, ...) { size_t len; char *retbuf; va_list argp; char *p; if(first == NULL) return NULL; len = strlen(first); va_start(argp, first); while((p = va_arg(argp, char *)) != NULL) len += strlen(p); va_end(argp); retbuf [...]]]></description>
			<content:encoded><![CDATA[<pre name="code" class="c">
#include <stdlib.h> /* 说明 malloc, NULL, size_t */
#include <stdarg.h> /* 说明 va_ 相关类型和函数 */
#include <string.h> /* 说明 strcat 等 */
char *vstrcat(const char *first, ...)
{
	size_t len;
	char *retbuf;
	va_list argp;
	char *p;
	if(first == NULL)
		return NULL;
	len = strlen(first);
	va_start(argp, first);
	while((p = va_arg(argp, char *)) != NULL)
		len += strlen(p);
	va_end(argp);

	retbuf = malloc(len + 1); /* +1 包含终止符 \0 */
	if(retbuf == NULL)
		return NULL; /* 出错 */
	(void)strcpy(retbuf, first);
	va_start(argp, first); /* 重新开始扫描 */
	while((p = va_arg(argp, char *)) != NULL)
		(void)strcat(retbuf, p);
	va_end(argp);
	retbuf = malloc(len + 1); /* +1 包含终止符 \0 */
	if(retbuf == NULL)
		return NULL; /* 出错 */
	(void)strcpy(retbuf, first);
	va_start(argp, first); /* 重新开始扫描 */
	while((p = va_arg(argp, char *)) != NULL)
		(void)strcat(retbuf, p);
	va_end(argp);
	return retbuf;
}
</pre>
<p>%c 一个单一的字符<br />
%d 一个十进制整数<br />
%i 一个整数<br />
%e, %f, %g 一个浮点数<br />
%o 一个八进制数<br />
%s 一个字符串<br />
%x 一个十六进制数<br />
%p 一个指针<br />
%n 一个等于读取字符数量的整数<br />
%u 一个无符号整数<br />
%[] 一个字符集<br />
%% 一个精度符号 </p>
<p>//一、NSString<br />
    /*&#8212;&#8212;&#8212;&#8212;&#8212;-创建字符串的方法&#8212;&#8212;&#8212;&#8212;&#8212;-*/</p>
<p>    1、创建常量字符串。<br />
    NSString *astring = @”This is a String!”;</p>
<p>    2、创建空字符串，给予赋值。<br />
    NSString *astring = [[NSString alloc] init];<br />
    astring = @”This is a String!”;<br />
    NSLog(@”astring:%@”,astring);<br />
    [astring release];</p>
<p>    3、在以上方法中，提升速度:initWithString方法<br />
    NSString *astring = [[NSString alloc] initWithString:@”This is a String!”];<br />
    NSLog(@”astring:%@”,astring);<br />
    [astring release];</p>
<p>    4、用标准c创建字符串:initWithCString方法<br />
    char *Cstring = “This is a String!”;<br />
    NSString *astring = [[NSString alloc] initWithCString:Cstring];<br />
    NSLog(@”astring:%@”,astring);<br />
    [astring release];</p>
<p>    5、创建格式化字符串:占位符（由一个%加一个字符组成）<br />
    int i = 1;<br />
    int j = 2;<br />
    NSString *astring = [[NSString alloc] initWithString:[NSString stringWithFormat:@"%d.This is %i string!",i,j]];<br />
    NSLog(@”astring:%@”,astring);<br />
    [astring release];</p>
<p>    6、创建临时字符串<br />
    NSString *astring;<br />
    astring = [NSString stringWithCString:"This is a temporary string"];<br />
    NSLog(@”astring:%@”,astring);</p>
<p>    /*&#8212;&#8212;&#8212;&#8212;&#8212;-从文件读取字符串:initWithContentsOfFile方法 &#8212;&#8212;&#8212;&#8212;&#8212;-*/<br />
    NSString *path = @”astring.text”;<br />
    NSString *astring = [[NSString alloc] initWithContentsOfFile:path];<br />
    NSLog(@”astring:%@”,astring);<br />
    [astring release];</p>
<p>    /*&#8212;&#8212;&#8212;&#8212;&#8212;-写字符串到文件:writeToFile方法 &#8212;&#8212;&#8212;&#8212;&#8212;-*/<br />
    NSString *astring = [[NSString alloc] initWithString:@”This is a String!”];<br />
    NSLog(@”astring:%@”,astring);<br />
    NSString *path = @”astring.text”;<br />
    [astring writeToFile: path atomically: YES];<br />
    [astring release];    </p>
<p>    /*&#8212;&#8212;&#8212;&#8212;&#8212;- 比较两个字符串&#8212;&#8212;&#8212;&#8212;&#8212;-*/<br />
    用C比较:strcmp函数<br />
    char string1[] = “string!”;<br />
    char string2[] = “string!”;<br />
    if(strcmp(string1, string2) = = 0)<br />
    {<br />
        NSLog(@”1&#8243;);<br />
    }</p>
<p>    isEqualToString方法<br />
    NSString *astring01 = @”This is a String!”;<br />
    NSString *astring02 = @”This is a String!”;<br />
    BOOL result = [astring01 isEqualToString:astring02];<br />
    NSLog(@”result:%d”,result);</p>
<p>    compare方法(comparer返回的三种值)<br />
    NSString *astring01 = @”This is a String!”;<br />
    NSString *astring02 = @”This is a String!”;<br />
    BOOL result = [astring01 compare:astring02] = = NSOrderedSame;<br />
    NSLog(@”result:%d”,result);<br />
    NSOrderedSame 判断两者内容是否相同</p>
<p>    NSString *astring01 = @”This is a String!”;<br />
    NSString *astring02 = @”this is a String!”;<br />
    BOOL result = [astring01 compare:astring02] = = NSOrderedAscending;<br />
    NSLog(@”result:%d”,result);<br />
    //NSOrderedAscending 判断两对象值的大小(按字母顺序进行比较，astring02大于astring01为真)</p>
<p>    NSString *astring01 = @”this is a String!”;<br />
    NSString *astring02 = @”This is a String!”;<br />
    BOOL result = [astring01 compare:astring02] = = NSOrderedDescending;<br />
    NSLog(@”result:%d”,result);<br />
    //NSOrderedDescending 判断两对象值的大小(按字母顺序进行比较，astring02小于astring01为真)</p>
<p>    不考虑大 小写比较字符串1<br />
    NSString *astring01 = @”this is a String!”;<br />
    NSString *astring02 = @”This is a String!”;<br />
    BOOL result = [astring01 caseInsensitiveCompare:astring02] = = NSOrderedSame;<br />
    NSLog(@”result:%d”,result);<br />
    //NSOrderedDescending判断两对象值的大小(按字母顺序进行比较，astring02小于astring01为 真)</p>
<p>    不考虑大小写比较字符串2<br />
    NSString *astring01 = @”this is a String!”;<br />
    NSString *astring02 = @”This is a String!”;<br />
    BOOL result = [astring01 compare:astring02<br />
                            options:NSCaseInsensitiveSearch | NSNumericSearch] = = NSOrderedSame;<br />
    NSLog(@”result:%d”,result);     </p>
<p>    //NSCaseInsensitiveSearch:不区分大小写比较 NSLiteralSearch:进行完全比较，区分大小写 NSNumericSearch:比较字符串的字符个数，而不是字符值。</p>
<p>    /*&#8212;&#8212;&#8212;&#8212;&#8212;-改变字符串的大小写&#8212;&#8212;&#8212;&#8212;&#8212;-*/<br />
    NSString *string1 = @”A String”;<br />
    NSString *string2 = @”String”;<br />
    NSLog(@”string1:%@”,[string1 uppercaseString]);//大写<br />
    NSLog(@”string2:%@”,[string2 lowercaseString]);//小写<br />
    NSLog(@”string2:%@”,[string2 capitalizedString]);//首字母大小</p>
<p>    /*&#8212;&#8212;&#8212;&#8212;&#8212;-在串中搜索子串 &#8212;&#8212;&#8212;&#8212;&#8212;-*/<br />
    NSString *string1 = @”This is a string”;<br />
    NSString *string2 = @”string”;<br />
    NSRange range = [string1 rangeOfString:string2];<br />
    int location = range.location;<br />
    int leight = range.length;<br />
    NSString *astring = [[NSString alloc] initWithString:[NSString stringWithFormat:@"Location:%i,Leight:%i",location,leight]];<br />
    NSLog(@”astring:%@”,astring);<br />
    [astring release];</p>
<p>    /*&#8212;&#8212;&#8212;&#8212;&#8212;-抽取子串 &#8212;&#8212;&#8212;&#8212;&#8212;-*/<br />
    -substringToIndex: 从字符串的开头一直截取到指定的位置，但不包括该位置的字符<br />
    NSString *string1 = @”This is a string”;<br />
    NSString *string2 = [string1 substringToIndex:3];<br />
    NSLog(@”string2:%@”,string2);</p>
<p>    -substringFromIndex: 以指定位置开始（包括指定位置的字符），并包括之后的全部字符<br />
    NSString *string1 = @”This is a string”;<br />
    NSString *string2 = [string1 substringFromIndex:3];<br />
    NSLog(@”string2:%@”,string2);</p>
<p>    -substringWithRange: //按照所给出的位置，长度，任意地从字符串中截取子串<br />
    NSString *string1 = @”This is a string”;<br />
    NSString *string2 = [string1 substringWithRange:NSMakeRange(0, 4)];<br />
    NSLog(@”string2:%@”,string2); </p>
<p>const char *fieldValue = [value  cStringUsingEncoding:NSUTF8StringEncoding];<br />
const char *fieldValue = [value UTF8String];</p>
<p>NSString 转 NSData<br />
NSString* str= @”kilonet”;<br />
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding]; </p>
<p>   Date format用法：<br />
  -(NSString *) getDay:(NSDate *) d<br />
{<br />
    NSString *s ;<br />
    NSDateFormatter *format = [[NSDateFormatter alloc] init];<br />
    [format setDateFormat:@"YYYY/MM/dd hh:mm:ss"];<br />
    s = [format stringFromDate:d];<br />
    [format release];<br />
    return s;<br />
}</p>
<p>各地时区获取：</p>
<p>代码<br />
    NSDate *nowDate = [NSDate new];<br />
    NSDateFormatter *formatter    =  [[NSDateFormatter alloc] init];<br />
    [formatter    setDateFormat:@"yyyy/MM/dd HH:mm:ss"];<br />
    //    根据时区名字获取当前时间，如果该时区不存在，默认获取系统当前时区的时间<br />
    //    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Europe/Andorra"];<br />
    //    [formatter setTimeZone:timeZone];<br />
    //获取所有的时区名字<br />
    NSArray *array = [NSTimeZone knownTimeZoneNames];<br />
    //    NSLog(@”array:%@”,array);<br />
    //for循环<br />
    //    for(int i=0;i<[array count];i++)<br />
    //    {<br />
    //        NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:[array objectAtIndex:i]];<br />
    //        [formatter setTimeZone:timeZone];<br />
    //        NSString *locationTime = [formatter stringFromDate:nowDate];<br />
    //        NSLog(@"时区名字:%@   : 时区当前时间: %@",[array objectAtIndex:i],locationTime);<br />
    //        //NSLog(@"timezone name is:%@",[array objectAtIndex:i]);<br />
    //    }<br />
    //快速枚举法<br />
    for(NSString *timeZoneName in array){<br />
        [formatter setTimeZone:[NSTimeZone timeZoneWithName:timeZoneName]];<br />
        NSLog(@"%@,%@",timeZoneName,[formatter stringFromDate:nowDate]);<br />
    }</p>
<p>    [formatter release];<br />
    [nowDate release];</p>
<p> NSCalendar用法：</p>
<p> -(NSString *) getWeek:(NSDate *) d {<br />
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];<br />
    unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSWeekdayCalendarUnit;<br />
    NSDateComponents *components = [calendar components:units fromDate:d];<br />
    [calendar release];</p>
<p>    switch ([components weekday]) {<br />
        case 2:<br />
            return @"Monday";<br />
            break;<br />
        case 3:<br />
            return @"Tuesday";<br />
            break;<br />
        case 4:<br />
            return @"Wednesday";<br />
            break;<br />
        case 5:<br />
           return @"Thursday";<br />
            break;<br />
        case 6:<br />
            return  @"Friday";<br />
            break;<br />
        case 7:<br />
            return  @"Saturday";<br />
            break;<br />
        case 1:<br />
            return @"Sunday";<br />
            break;<br />
        default:<br />
            return @"No Week";<br />
            break;<br />
    }</p>
<p>    // 用components，我们可以读取其他更多的数据。</p>
<p>}</p>
<p>4. 用Get方式读取网络数据：</p>
<p>将网络数读取为字符串<br />
- (NSString *) getDataByURL:(NSString *) url {<br />
    return [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]] encoding:NSUTF8StringEncoding];<br />
}</p>
<p>//读取网络图片<br />
- (UIImage *) getImageByURL:(NSString *) url {<br />
    return [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];<br />
}</p>
<p>多线程<br />
[NSThread detachNewThreadSelector:@selector(scheduleTask) toTarget:self withObject:nil];</p>
<p>-(void) scheduleTask {<br />
    //create a pool<br />
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];</p>
<p>    //release the pool;<br />
    [pool release];<br />
}</p>
<p>//如果有参数，则这么使用：<br />
[NSThread detachNewThreadSelector:@selector(scheduleTask:) toTarget:self withObject:[NSDate date]];</p>
<p>-(void) scheduleTask:(NSDate *) mdate {<br />
    //create a pool<br />
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];</p>
<p>    //release the pool;<br />
    [pool release];<br />
}</p>
<p>//注意selector里有冒号。<br />
    //在线程里运行主线程里的方法 </p>
<p>    [self performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE];</p>
<p>6. 定时器NSTimer用法:</p>
<p>代码<br />
  // 一个可以自动关闭的Alert窗口</p>
<p>    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil<br />
                                                    message:[@"一个可以自动关闭的Alert窗口"<br />
                                                   delegate:nil<br />
                                          cancelButtonTitle:nil //NSLocalizedString(@"OK", @"OK")   //取消任何按钮<br />
                                          otherButtonTitles:nil];<br />
    //[alert setBounds:CGRectMake(alert.bounds.origin.x, alert.bounds.origin.y, alert.bounds.size.width, alert.bounds.size.height+30.0)];<br />
    [alert show];</p>
<p>    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];</p>
<p>    // Adjust the indicator so it is up a few pixels from the bottom of the alert<br />
    indicator.center = CGPointMake(alert.bounds.size.width/2,  alert.bounds.size.height-40.0);<br />
    [indicator startAnimating];<br />
    [alert insertSubview:indicator atIndex:0];<br />
    [indicator release];</p>
<p>    [NSTimer scheduledTimerWithTimeInterval:3.0f<br />
                                     target:self<br />
                                   selector:@selector(dismissAlert:)<br />
                                   userInfo:[NSDictionary dictionaryWithObjectsAndKeys:alert, @"alert", @"testing ", @"key" ,nil]  //如果不用传递参数，那么可以将此项设置为nil.<br />
                                    repeats:NO];</p>
<p>    NSLog(@"release alert");<br />
    [alert release];</p>
<p>-(void) dismissAlert:(NSTimer *)timer{</p>
<p>    NSLog(@"release timer");<br />
    NSLog([[timer userInfo]  objectForKey:@"key"]);</p>
<p>    UIAlertView *alert = [[timer userInfo]  objectForKey:@"alert"];<br />
    [alert dismissWithClickedButtonIndex:0 animated:YES];</p>
<p>}</p>
<p>定时器停止使用：</p>
<p>[timer invalidate];<br />
timer = nil;</p>
<p>     7. 用户缺省值NSUserDefaults读取：</p>
<p>    //得到用户缺省值<br />
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];</p>
<p>    //在缺省值中找到AppleLanguages, 返回值是一个数组<br />
    NSArray* languages = [defs objectForKey:@"AppleLanguages"];<br />
    NSLog(@"all language语言 is %@", languages);</p>
<p>    //在得到的数组中的第一个项就是用户的首选语言了<br />
    NSLog(@"首选语言 is %@",[languages objectAtIndex:0]);  </p>
<p>    //get the language &#038; country code<br />
    NSLocale *currentLocale = [NSLocale currentLocale];</p>
<p>    NSLog(@"Language Code is %@", [currentLocale objectForKey:NSLocaleLanguageCode]);<br />
    NSLog(@"Country Code is %@", [currentLocale objectForKey:NSLocaleCountryCode</p>
<p>8. View之间切换的动态效果设置：</p>
<p>    SettingsController *settings = [[SettingsController alloc]initWithNibName:@"SettingsView" bundle:nil];<br />
    settings.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;  //水平翻转<br />
    [self presentModalViewController:settings animated:YES];<br />
    [settings release];</p>
<p>9.NSScrollView 滑动用法：</p>
<p>-(void) scrollViewDidScroll:(UIScrollView *)scrollView{<br />
    NSLog(@"正在滑动中...");<br />
}</p>
<p>//用户直接滑动NSScrollView，可以看到滑动条<br />
-(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {</p>
<p>}</p>
<p>// 通过其他控件触发NSScrollView滑动，看不到滑动条<br />
- (void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {</p>
<p>}</p>
<p>    11.键盘处理系列</p>
<p> //set the UIKeyboard to switch to a different text field when you press return</p>
<p>//switch textField to the name of your textfield<br />
[textField becomeFirstResponder];</p>
<p>srandom(time(NULL)); //随机数种子</p>
<p>id d = random(); // 随机数</p>
<p>   4. iPhone的系统目录:</p>
<p>//得到Document目录：<br />
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);<br />
NSString *documentsDirectory = [paths objectAtIndex:0];</p>
<p>//得到temp临时目录：<br />
NSString *tempPath = NSTemporaryDirectory();</p>
<p>//得到目录上的文件地址：<br />
NSString *文件地址 = [目录地址 stringByAppendingPathComponent:@"文件名.扩展名"];</p>
<p> 5. 状态栏显示Indicator：</p>
<p>[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; </p>
<p>  6.app Icon显示数字：</p>
<p>- (void)applicationDidEnterBackground:(UIApplication *)application{<br />
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:5];<br />
}</p>
<p>   7.sqlite保存地址： </p>
<p>代码<br />
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);<br />
    NSString *thePath = [paths objectAtIndex:0];<br />
    NSString *filePath = [thePath stringByAppendingPathComponent:@"kilonet1.sqlite"];</p>
<p>    NSString *dbPath = [[[NSBundle mainBundle] resourcePath]<br />
                        stringByAppendingPathComponent:@"kilonet2.sqlite"]; </p>
<p>   8.Application退出：exit(0);</p>
<p>      9. AlertView，ActionSheet的cancelButton点击事件：</p>
<p>代码<br />
-(void) actionSheet <img src='http://www.wezu.net/blog/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> UIActionSheet *) actionSheet didDismissWithButtonIndex:(NSInteger) buttonIndex {<br />
    NSLog(@"cancel actionSheet........");<br />
    //当用户按下cancel按钮<br />
    if( buttonIndex == [actionSheet cancelButtonIndex]) {<br />
        exit(0);<br />
    }<br />
//    //当用户按下destructive按钮<br />
//    if( buttonIndex == [actionSheet destructiveButtonIndex]) {<br />
//        // DoSomething here.<br />
//    }<br />
}</p>
<p>- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {<br />
     NSLog(@"cancel alertView........");<br />
    if (buttonIndex == [alertView cancelButtonIndex]) {<br />
        exit(0);<br />
    }<br />
}</p>
<p>  10.给Window设置全局的背景图片：<br />
window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"coolblack.png"]];</p>
<p>    11. UITextField文本框显示及对键盘的控制:</p>
<p>代码<br />
#pragma mark -<br />
#pragma mark UITextFieldDelegate<br />
//控制键盘跳转<br />
- (BOOL)textFieldShouldReturn:(UITextField *)textField {</p>
<p>    if (textField == _txtAccount) {<br />
        if ([_txtAccount.text length]==0) {<br />
            return NO;<br />
        }<br />
        [_txtPassword becomeFirstResponder];<br />
    } else if (textField == _txtPassword) {<br />
        [_txtPassword resignFirstResponder];<br />
    }</p>
<p>    return YES;<br />
}</p>
<p>//输入框背景更换<br />
-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField{</p>
<p>    [textField setBackground:[UIImage imageNamed:@"ctext_field_02.png"]];</p>
<p>    return YES;<br />
}</p>
<p>-(void) textFieldDidEndEditing:(UITextField *)textField{<br />
    [textField setBackground:[UIImage imageNamed:@"ctext_field_01.png"]];<br />
}</p>
<p>12.UITextField文本框前面空白宽度设置以及后面组合按钮设置：</p>
<p>代码<br />
    //给文本输入框后面加入空白<br />
    _txtAccount.rightView = _btnDropDown;<br />
    _txtAccount.rightViewMode =  UITextFieldViewModeAlways;</p>
<p>    //给文本输入框前面加入空白<br />
    CGRect frame = [_txtAccount frame];<br />
    frame.size.width = 5;<br />
    UIView *leftview = [[UIView alloc] initWithFrame:frame];<br />
    _txtAccount.leftViewMode = UITextFieldViewModeAlways;<br />
    _txtAccount.leftView = leftview;</p>
<p>  13. UIScrollView 设置滑动不超出本身范围：</p>
<p> [fcScrollView setBounces:NO]; </p>
<p>    14. 遍历View里面所有的Subview：</p>
<p>代码<br />
    NSLog(@"subviews count=%d",[self.view.subviews count]);<br />
    if ([self.view.subviews count] > 0) {<br />
        for (UIView *curView in self.view.subviews) {<br />
                       NSLog(@”view.subviews=%@”, [NSString stringWithUTF8String:object_getClassName(curView)]);<br />
        }<br />
    }</p>
<p> 14. 在drawRect里画文字：</p>
<p>     UIFont * f = [UIFont systemFontOfSize:20]; </p>
<p>    [[UIColor darkGrayColor] set]; </p>
<p>    NSString * text = @”hi \nKiloNet”; </p>
<p>    [text drawAtPoint:CGPointMake(center.x,center.y) withFont:f];</p>
<p>    15. NSArray查找是否存在对象时用indexOfObject,如果不存在则返回为NSNotFound.</p>
<p>    16. NString与NSArray之间相互转换：</p>
<p>array = [string componentsSeparatedByString:@","];<br />
string = [[array valueForKey:@"description"] componentsJoinedByString:@”,”];</p>
<p>     17. TabController随意切换tab bar：</p>
<p>[self.tabBarController setSelectedIndex:tabIndex];</p>
<p>或者 self.tabBarController.selectedIndex = tabIndex;</p>
<p>或者实现下面的delegate来扑捉tab bar的事件： </p>
<p>代码-(BOOL) tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {        if ([viewController.tabBarItem.title isEqualToString: NSLocalizedString(@"Logout",nil)]) {        [self showLogout];        return NO;    }    return YES;}</p>
<p>    18. 自定义View之间切换动画：<br />
代码<br />
- (void) pushController: (UIViewController*) controller<br />
         withTransition: (UIViewAnimationTransition) transition<br />
{<br />
    [UIView beginAnimations:nil context:NULL];<br />
    [self pushViewController:controller animated:NO];<br />
    [UIView setAnimationDuration:.5];<br />
    [UIView setAnimationBeginsFromCurrentState:YES];<br />
    [UIView setAnimationTransition:transition forView:self.view cache:YES];<br />
    [UIView commitAnimations];<br />
}</p>
<p>CATransition *transition = [CATransition animation];<br />
transition.duration = kAnimationDuration;<br />
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];<br />
transition.type = kCATransitionPush;<br />
transition.subtype = kCATransitionFromTop;<br />
transitioning = YES;<br />
transition.delegate = self;<br />
[self.navigationController.view.layer addAnimation:transition forKey:nil];</p>
<p>self.navigationController.navigationBarHidden = NO;<br />
[self.navigationController pushViewController:tableViewController animated:YES];</p>
<p>     20.计算字符串长度：</p>
<p>CGFloat w = [title sizeWithFont:[UIFont fontWithName:@"Arial" size:18]].width; </p>
<p>  23.在使用UISearchBar时，将背景色设定为clearColor，或者将translucent设为YES，都不能使背景透明，经过一番研究，发现了一种超级简单和实用的方法：</p>
<p>1<br />
 [[searchbar.subviews objectAtIndex:0]removeFromSuperview]; </p>
<p>背景完全消除了，只剩下搜索框本身了。 </p>
<p>  24.  图像与缓存 :</p>
<p>UIImageView *wallpaper = [[UIImageView alloc] initWithImage:</p>
<p>        [UIImage imageNamed:@"icon.png"]]; // 会缓存图片</p>
<p>UIImageView *wallpaper = [[UIImageView alloc] initWithImage:</p>
<p>        [UIImage imageWithContentsOfFile:@"icon.png"]]; // 不会缓存图片 </p>
<p>  25. iphone-常用的对视图图层(layer)的操作</p>
<p>对图层的操作：</p>
<p>(1.给图层添加背景图片：<br />
myView.layer.contents = (id)[UIImage imageNamed:@"view_BG.png"].CGImage;</p>
<p>(2.将图层的边框设置为圆脚<br />
myWebView.layer.cornerRadius = 8;<br />
myWebView.layer.masksToBounds = YES;</p>
<p>(3.给图层添加一个有色边框<br />
myWebView.layer.borderWidth = 5;<br />
myWebView.layer.borderColor = [[UIColor colorWithRed:0.52 green:0.09 blue:0.07 alpha:1] CGColor];</p>
]]></content:encoded>
			<wfw:commentRss>http://www.wezu.net/blog/archives/86/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Delphi窗口抖动代码</title>
		<link>http://www.wezu.net/blog/archives/68</link>
		<comments>http://www.wezu.net/blog/archives/68#comments</comments>
		<pubDate>Fri, 20 Aug 2010 03:15:22 +0000</pubDate>
		<dc:creator>snox</dc:creator>
				<category><![CDATA[代码片断]]></category>
		<category><![CDATA[Delphi 窗口抖动]]></category>

		<guid isPermaLink="false">http://www.wezu.net/blog/?p=68</guid>
		<description><![CDATA[var i, t, l : Integer; begin btnDemo.Enabled := False; t := Self.Top; l := Self.Left; for i := 0 to 20 do begin case (i mod 4) of 0: begin Self.Top := t + 2; Self.Left := l + 2; end; 1: begin Self.Top := t + 2; Self.Left := l - 2; end; [...]]]></description>
			<content:encoded><![CDATA[<pre name="code" class="Delphi">
var
  i, t, l     : Integer;
begin
  btnDemo.Enabled := False;
  t := Self.Top;
  l := Self.Left;

  for i := 0 to 20 do
  begin

    case (i mod 4) of
    0:
      begin
        Self.Top  := t + 2;
        Self.Left := l + 2;
      end;
    1:
      begin
        Self.Top  := t + 2;
        Self.Left := l - 2;
      end;
    2:
      begin
        Self.Top  := t - 2;
        Self.Left := l - 2;
      end;
    3:
      begin
        Self.Top  := t - 2;
        Self.Left := l + 2;
      end;
    end;
    Application.ProcessMessages;

    //Sleep(50);
    SleepEx(50, True);
  end;
  Self.Top  := t;
  Self.Left := l;

  btnDemo.Enabled := True;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.wezu.net/blog/archives/68/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>让你的程序具备XP风格</title>
		<link>http://www.wezu.net/blog/archives/7</link>
		<comments>http://www.wezu.net/blog/archives/7#comments</comments>
		<pubDate>Tue, 25 Dec 2007 09:19:03 +0000</pubDate>
		<dc:creator>snox</dc:creator>
				<category><![CDATA[代码片断]]></category>

		<guid isPermaLink="false">http://www.wezu.net/blog/?p=7</guid>
		<description><![CDATA[  以上说的适用于MFC，如果用win32   sdk的话，还是应该参照MSDN.     只不过MFC7.1把以下这些自动化了。         大意是：（我用xpstyle代表项目名）         1。做一个xml文件：xpstyle.manifest      Your application description here.           2.程序初始化时，运行     InitCommonControls();         3.在resoure.h中加       #define   IDR_MANIFEST CREATEPROCESS_MANIFEST_RESOURCE_ID           4.在xpstyle.rc中加         #ifdef   _UNICODE     IDR_MANIFEST RT_MANIFEST "res\\xpstyle.manifest     #endif         5.最后还是要将项目设为UNICODE字符集编译。         6.另外，如果写dll,或者其他的,参照(MSDN2003-4)             ms-help://MS.MSDNQTR.2003APR.1033/shellcc/platform/commctls/userex/cookbook.htm#no_extensions]]></description>
			<content:encoded><![CDATA[<p>  以上说的适用于MFC，如果用win32   sdk的话，还是应该参照MSDN.  <br />
  只不过MFC7.1把以下这些自动化了。  <br />
   <br />
  大意是：（我用xpstyle代表项目名）  <br />
   <br />
  1。做一个xml文件：xpstyle.manifest     </p>
<pre lang="xml">
<?xml   version="1.0"   encoding="UTF-8"   standalone="yes"?>
  <assembly   xmlns="urn:schemas-microsoft-com:asm.v1"   manifestVersion="1.0">
  <assemblyIdentity
          version="1.0.0.0"
          processorArchitecture="X86"
          name="CompanyName.ProductName.xpstyle"
          type="win32"
  />
  <description>Your   application   description   here.</description>
  <dependency>
          <dependentAssembly>
                  <assemblyIdentity
                          type="win32"
                          name="Microsoft.Windows.Common-Controls"
                          version="6.0.0.0"
                          processorArchitecture="X86"
                          publicKeyToken="6595b64144ccf1df"
                          language="*"
                  />
          </dependentAssembly>
  </dependency>
  </assembly></pre>
<p>   <br />
   <br />
  2.程序初始化时，运行  <br />
 
<pre lang="cpp">InitCommonControls();  </pre>
<p>   <br />
  3.在resoure.h中加  <br />
   
<pre lang="cpp">#define   IDR_MANIFEST CREATEPROCESS_MANIFEST_RESOURCE_ID    </pre>
<p>   <br />
  4.在xpstyle.rc中加  <br />
   <br />
 
<pre lang="cpp">#ifdef   _UNICODE  
  IDR_MANIFEST RT_MANIFEST "res\\xpstyle.manifest  </pre>
<p>  #endif  <br />
   <br />
  5.最后还是要将项目设为UNICODE字符集编译。  <br />
   <br />
  6.另外，如果写dll,或者其他的,参照(MSDN2003-4)  <br />
   <br />
      ms-help://MS.MSDNQTR.2003APR.1033/shellcc/platform/commctls/userex/cookbook.htm#no_extensions</p>
]]></content:encoded>
			<wfw:commentRss>http://www.wezu.net/blog/archives/7/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IExtractImage</title>
		<link>http://www.wezu.net/blog/archives/3</link>
		<comments>http://www.wezu.net/blog/archives/3#comments</comments>
		<pubDate>Thu, 01 Nov 2007 17:30:47 +0000</pubDate>
		<dc:creator>snox</dc:creator>
				<category><![CDATA[代码片断]]></category>

		<guid isPermaLink="false">http://www.wezu.net/blog/?p=3</guid>
		<description><![CDATA[void* CShellListCtrl::GetThumbnailImage(CString &#38;fileName, int longestEdge, int colorDepth) {  // divide the file name into a folder path and file name.  WCHAR wDirName[MAX_PATH];  WCHAR wFileName[MAX_PATH];  CString dir = fileName.Left(fileName.ReverseFind('\\'));  CString file = fileName.Right(fileName.GetLength() - dir.GetLength() - 1);  TCHAR tName[MAX_PATH];  strcpy(tName, dir.GetBuffer());  wcscpy(wDirName, CT2W(tName));    strcpy(tName, file.GetBuffer());  wcscpy(wFileName, CT2W(tName));  IShellFolder* pDesktop = NULL;  IShellFolder* pSub = NULL;  IExtractImage* pIExtract = [...]]]></description>
			<content:encoded><![CDATA[<pre lang="cpp" lineno="1">void* CShellListCtrl::GetThumbnailImage(CString &amp;fileName, int longestEdge, int colorDepth)
{
 // divide the file name into a folder path and file name.
 WCHAR wDirName[MAX_PATH];
 WCHAR wFileName[MAX_PATH];
 CString dir = fileName.Left(fileName.ReverseFind('\\'));
 CString file = fileName.Right(fileName.GetLength() - dir.GetLength() - 1);
 TCHAR tName[MAX_PATH];
 strcpy(tName, dir.GetBuffer());
 wcscpy(wDirName, CT2W(tName));
 
 strcpy(tName, file.GetBuffer());
 wcscpy(wFileName, CT2W(tName));
 IShellFolder* pDesktop = NULL;
 IShellFolder* pSub = NULL;
 IExtractImage* pIExtract = NULL;
 LPITEMIDLIST pList = NULL;
 HBITMAP   hBmp = NULL;

 // get the desktop directory
 if (SUCCEEDED(SHGetDesktopFolder(&amp;pDesktop)))
 {
  // get the pidl for the directory
  HRESULT hr = pDesktop-&gt;ParseDisplayName(NULL, NULL, wDirName, NULL, &amp;pList, NULL);
  if (FAILED(hr))
  { 
   throw new CUserInterfaceException("Failed to parse the directory name");
  }

  // get the directory IShellFolder interface
  hr = pDesktop-&gt;BindToObject(pList, NULL, IID_IShellFolder, (void**)&amp;pSub);
  if (FAILED(hr))
  {
   throw new CUserInterfaceException("Failed to bind to the directory");
  }

  // get the file's pidl
  hr = pSub-&gt;ParseDisplayName(NULL, NULL, wFileName, NULL, &amp;pList, NULL);
  if (FAILED(hr))
  {
   throw new CUserInterfaceException("Failed to parse the file name");
  }

  // get the IExtractImage interface
  LPCITEMIDLIST pidl = pList;
  hr = pSub-&gt;GetUIObjectOf(NULL, 1, &amp;pidl, IID_IExtractImage, NULL, (void**)&amp;pIExtract);
  
  // set our desired image size
  SIZE size;
  size.cx = longestEdge;
  size.cy = longestEdge;     
  
  if(pIExtract == NULL)
  {
   return NULL;
  }        

  // The IEIFLAG_ORIGSIZE flag tells it to use the original aspect
  // ratio for the image size. The IEIFLAG_QUALITY flag tells the
  // interface we want the image to be the best possible quality.
  DWORD dwFlags = IEIFLAG_ORIGSIZE | IEIFLAG_QUALITY;     
  
  OLECHAR pathBuffer[MAX_PATH];
  hr = pIExtract-&gt;GetLocation(pathBuffer, MAX_PATH, NULL, &amp;size, colorDepth, &amp;dwFlags);        
  if (FAILED(hr))
  {
   throw new CUserInterfaceException("The call to GetLocation failed");
  }

  hr = pIExtract-&gt;Extract(&amp;hBmp);  //THIS IS WHERE I GET THE ERROR MESSAGE

  pIExtract-&gt;Release();
 } // if

 // Release the COM objects we have a reference to.
 pDesktop-&gt;Release();
 pSub-&gt;Release();

 return hBmp;
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.wezu.net/blog/archives/3/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

