iphone小技巧1

这里记录一些收集到的小技巧。

 

这里有很多Demo  http://www.cocoachina.com/bbs/read.php?tid-12269.html

 

1:改变按钮状态

[button setTitle:@"未按" forState:UIControlStateNormal];
[button setTitle:@"已按" forState:UIControlStateHighlighted];
[button setBackgroundImage:[UIImage imageNamed:@"1.png"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"2.png"] forState:UIControlStateHighlighted];

2:自定义UINavigationBar背景图片

在网上找到的显示自定义UINavigationBar背景图片的例子代码,发现没有自己想要的,或者好用的,
于是,根据网上的例子,自己编写了下面的一段代码,希望可以给想要的人帮助。

调用很简单,就不介绍了;
在drawDraw方法中注释掉的代码,事用来自定义UINavigationBar背景色的,
如果想用,可以参考自定义图片的方法。


//
//  myCustomNavigationBarImage.h
//

#import <Foundation/Foundation.h>

@interface UINavigationBar (CustomImage)

- (void) drawRect: (CGRect)rect;
- (void) setImage: (NSString *)image;

@end

//
//  myCustomNavigationBarImage.m
//

#import "myCustomNavigationBarImage.h"

static UIImage *barImage = nil;

@implementation UINavigationBar (CustomImage)

- (void) drawRect: (CGRect)rect
{
    if (barImage != nil)
    {
        [barImage drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        [barImage release];
        barImage = nil;
    }
    else
    {
//        UIColor *color = [UIColor redColor];
//        CGContextRef context = UIGraphicsGetCurrentContext();
//        CGContextSetFillColor(context, CGColorGetComponents( [color CGColor]));
//        CGContextFillRect(context, rect);
//        self.tintColor = color;
    }

}

- (void) setImage: (NSString *)image
{
    barImage = [ UIImage imageNamed:image];
    [self setNeedsDisplay];
}
@end

 

 

3:iphone/ipad设置背景图片

方法一,使用一个UIImageView实例做子视图,并且放最后面
- (void)setBackgroundImage {
NSLog(@"setting bg image");
UIImageView *customBackground = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.jpg"]];
self.background = customBackground;
[customBackground release];

[self addSubview:background];
NSLog(@"Added background subview %@", background);
[self sendSubviewToBack:background];
}

方法二,Cook Book中提到的方法
- (void)loadView {

UIImageView *contentView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
[contentView setImage:[UIImage imageNamed:@"Default.png"]];
[contentView setUserInteractionEnabled:YES];
self.view = contentView;
[contentView release];
}

方法三,uiView是UIView的实例,而不是UIImageView
uiView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Default.png"]];

 

 

4:objective-c 解析html

 

  本段在 Objective-C 中解析 html 的代码由 CocoaChina 会员 “月华如水” 分享,希望对开发者们有所帮助


#import "StringChuLi.h"
/*
项目作用:链接网络解析html
 */

@implementation StringChuLi

//访问网页源码
-(NSString *)urlString:(NSString *)value{
NSURL *url = [NSURL URLWithString:value];
NSData *data = [NSData dataWithContentsOfURL:url]; 
//解决中文乱码,用GBK
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);   
NSString *retStr = [[NSString alloc] initWithData:data encoding:enc];
return retStr;
}
/*
 作用:截取从value1到value2之间的字符串
 str:要处理的字符串
 value1:左边匹配字符串
 value2:右边匹配字符串
 */
-(NSString *)str:(NSString *)str value1:(NSString *)value1 value2:(NSString *)value2{
//i:左边匹配字符串在str中的下标
int i;
//j:右边匹配字符串在str1中的下标
int j;
//该类可以通过value1匹配字符串
NSRange range1 = [str rangeOfString:value1];
//判断range1是否匹配到字符串
if(range1.length>0){
//把其转换为NSString
NSString *result1 = NSStringFromRange(range1);
i = [self indexByValue:result1];
//原因:加上匹配字符串的长度从而获得正确的下标
i = i+[value1 length];
}
//通过下标,删除下标以前的字符
NSString *str1 = [str substringFromIndex:i];
NSRange range2 = [str1 rangeOfString:value2];
if(range2.length>0){
NSString *result2 = NSStringFromRange(range2);
j = [self indexByValue:result2];
}
NSString *str2 = [str1 substringToIndex:j];
return str2;
}

//过滤获得的匹配信息的下标
-(int)indexByValue:(NSString *)str{
//使用NSMutableString类,它可以实现追加
NSMutableString *value = [[NSMutableString alloc] initWithFormat:@""];
NSString *colum2 = @"";
int j = 0;
//遍历出下标值
for(int i=1;i<[str length];i++){
NSString *colum1 = [str substringFromIndex:i];
[value appendString:colum2];
colum2 = [colum1 substringToIndex:1];
if([colum2 isEqualToString:@","]){
j = [value intValue];
break;
}
}
[value release];
return j;
}
@end

5:对Plist文件进行读写

p.p1 { margin: 0px; font-family: Monaco; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; }p.p2 { margin: 0px; font-family: Monaco; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; color: rgb(110, 52, 171); }p.p3 { margin: 0px; font-family: Monaco; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; color: rgb(60, 16, 130); }p.p4 { margin: 0px; font-family: Monaco; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; color: rgb(83, 129, 135); }p.p5 { margin: 0px; font-family: Monaco; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; color: rgb(203, 44, 30); }p.p6 { margin: 0px; font-family: Monaco; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; min-height: 19px; }p.p7 { margin: 0px; font-family: Monaco; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; color: rgb(182, 28, 164); }span.s1 { font-family: 'Heiti SC Light'; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; letter-spacing: 0px; }span.s2 { letter-spacing: 0px; }span.s3 { }span.s4 { }span.s5 { }span.s6 { }span.s7 { }span.s8 { }span.s9 { }span.s10 { }span.Apple-tab-span { white-space: pre; }

Plist 文件

NSString *errorDesc = nil ;

NSPropertyListFormat format;

NSString *rootPath = [ NSSearchPathForDirectoriesInDomains ( NSDocumentDirectory , NSUserDomainMask , YES ) objectAtIndex : 0 ];

NSString *plistPath = [rootPath stringByAppendingPathComponent : @"bookmarks.plist" ];

if (![[ NSFileManager defaultManager ] fileExistsAtPath :plistPath]) {

plistPath = [[ NSBundle mainBundle ] pathForResource : @"bookmarks" ofType : @"plist" ];

}

NSData *plistXML = [[ NSFileManager defaultManager ] contentsAtPath :plistPath];

context . bookmarksDic = ( NSMutableDictionary *)[[ NSPropertyListSerialization propertyListFromData :plistXML mutabilityOption : NSPropertyListMutableContainersAndLeaves

format :&format

errorDescription :&errorDesc] retain];

keysArr = [[[ context . bookmarksDic allKeys ] sortedArrayUsingSelector : @selector ( compare :)] retain ];

if (! context . bookmarksDic ) {

NSLog ( @"Error reading plist: %@, format: %d" , errorDesc, format);

}

 

写入 Plist

Context * context = [ Context getInstance ];

NSString *rootPath = [ NSSearchPathForDirectoriesInDomains ( NSDocumentDirectory ,

NSUserDomainMask , YES ) objectAtIndex : 0 ];

NSString *plistPath = [rootPath stringByAppendingPathComponent : @"bookmarks.plist" ];

NSString *error;

NSData *plistData = [ NSPropertyListSerialization dataFromPropertyList : context . bookmarksDic

format : NSPropertyListXMLFormat_v1_0

errorDescription :&error];

if (plistData) {

[plistData writeToFile :plistPath atomically : YES ];

}

else {

NSLog ( @"%@" ,error);

[error release ];

}

 

 

 

6:按钮加事件

[button addTarget:self

 action:@selector(buttonClicked:)

 forControlEvents:UIControlEventTouchUpInside];

 

7:比较系统版本

        NSString *reqSysVer = @"3.1";
        NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
       
        if([currSysVer compare:reqSysVer options:NSNumericSearch] == NSOrderedAscending)
            return NO;

 

 

 

8:国际化支持

1先在代码里用 NSLocalizedString(@"One",@"The number 1");替代你的字符串,

最后打开Finder 将LocalizeMe项目文件夹拖动到终端窗口中,

命令,genstrings ./Classes/*.m

将会生产,Localizable.strings文件

 

修改UIAlertView颜色

 

[CustomAlert setBackgroundColor:[UIColor blueColor]
 withStrokeColor:[UIColor greenColor]];
CustomAlert.h
#import <UIKit/UIKit.h>
 
@interface CustomAlert : UIAlertView
{
 
}
 
+ (void) setBackgroundColor:(UIColor *) background
 withStrokeColor:(UIColor *) stroke;
 
@end
CustomAlert.m
#import "CustomAlert.h"
 
@interface CustomAlert (Private)
 
- (void) drawRoundedRect:(CGRect) rect inContext:(CGContextRef)
 context withRadius:(CGFloat) radius;
 
@end
 
static UIColor *fillColor = nil;
static UIColor *borderColor = nil;
 
@implementation CustomAlert
 
+ (void) setBackgroundColor:(UIColor *) background
 withStrokeColor:(UIColor *) stroke
{
 if(fillColor != nil)
 {
  [fillColor release];
  [borderColor release];
 }
 
 fillColor = [background retain];
 borderColor = [stroke retain];
}
 
- (id)initWithFrame:(CGRect)frame
{
    if((self = [super initWithFrame:frame]))
 {
        if(fillColor == nil)
  {
   fillColor = [[UIColor blackColor] retain];
   borderColor = [[UIColor colorWithHue:0.625
    saturation:0.0 brightness:0.8 alpha:0.8]
     retain];
  }
    }
 
    return self;
}
 
- (void)layoutSubviews
{
 for (UIView *sub in [self subviews])
 {
  if([sub class] == [UIImageView class] && sub.tag == 0)
  {
   // The alert background UIImageView tag is 0,
   // if you are adding your own UIImageView's
   // make sure your tags != 0 or this fix
   // will remove your UIImageView's as well!
   [sub removeFromSuperview];
   break;
  }
 }
}
 
- (void)drawRect:(CGRect)rect

 CGContextRef context = UIGraphicsGetCurrentContext();
 
 CGContextClearRect(context, rect);
 CGContextSetAllowsAntialiasing(context, true);
 CGContextSetLineWidth(context, 0.0);
 CGContextSetAlpha(context, 0.8);
 CGContextSetLineWidth(context, 2.0);
 CGContextSetStrokeColorWithColor(context, [borderColor CGColor]);
 CGContextSetFillColorWithColor(context, [fillColor CGColor]);
 
 // Draw background
 CGFloat backOffset = 2;
 CGRect backRect = CGRectMake(rect.origin.x + backOffset,
  rect.origin.y + backOffset,
  rect.size.width - backOffset*2,
  rect.size.height - backOffset*2);
 
 [self drawRoundedRect:backRect inContext:context withRadius:8];
 CGContextDrawPath(context, kCGPathFillStroke);
 
 // Clip Context
 CGRect clipRect = CGRectMake(backRect.origin.x + backOffset-1,
  backRect.origin.y + backOffset-1,
  backRect.size.width - (backOffset-1)*2,
  backRect.size.height - (backOffset-1)*2);
 
 [self drawRoundedRect:clipRect inContext:context withRadius:8];
 CGContextClip (context);
 
 //Draw highlight
 CGGradientRef glossGradient;
 CGColorSpaceRef rgbColorspace;
 size_t num_locations = 2;
 CGFloat locations[2] = { 0.0, 1.0 };
 CGFloat components[8] = { 1.0, 1.0, 1.0, 0.35, 1.0, 1.0, 1.0, 0.06 };
 rgbColorspace = CGColorSpaceCreateDeviceRGB();
 glossGradient = CGGradientCreateWithColorComponents(rgbColorspace,
  components, locations, num_locations);
 
 CGRect ovalRect = CGRectMake(-130, -115, (rect.size.width*2),
  rect.size.width/2);
 
 CGPoint start = CGPointMake(rect.origin.x, rect.origin.y);
 CGPoint end = CGPointMake(rect.origin.x, rect.size.height/5);
 
 CGContextSetAlpha(context, 1.0);
 CGContextAddEllipseInRect(context, ovalRect);
 CGContextClip (context);
 
 CGContextDrawLinearGradient(context, glossGradient, start, end, 0);
 
 CGGradientRelease(glossGradient);
 CGColorSpaceRelease(rgbColorspace);
}
 
- (void) drawRoundedRect:(CGRect) rrect inContext:(CGContextRef) context
  withRadius:(CGFloat) radius
{
 CGContextBeginPath (context);
 
 CGFloat minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect),
  maxx = CGRectGetMaxX(rrect);
 
 CGFloat miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect),
  maxy = CGRectGetMaxY(rrect);
 
 CGContextMoveToPoint(context, minx, midy);
 CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
 CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
 CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
 CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
 CGContextClosePath(context);
}
 
- (void)dealloc
{
    [super dealloc];
}
 
@end

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值