iPhone 键盘

#define SCROLLVIEW_CONTENT_HEIGHT_PORTRAIT	610
#define SCROLLVIEW_CONTENT_WIDTH_PORTRAIT	320
#define SCROLLVIEW_CONTENT_HEIGHT_LANDSCAPE 500
#define SCROLLVIEW_CONTENT_WIDTH_LANDSCAPE	480

....

- (void)viewWillAppear:(BOOL)animated 
{
	[super viewWillAppear:animated];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) 
										name: UIKeyboardDidShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) 
										name: UIKeyboardDidHideNotification object:nil];
	
	m_scrollView.contentSize = CGSizeMake(SCROLLVIEW_CONTENT_WIDTH_PORTRAIT, SCROLLVIEW_CONTENT_HEIGHT_PORTRAIT);	
	displayKeyboard = NO;
}

- (void)viewWillDisappear:(BOOL)animated 
{
	[super viewWillDisappear:animated];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)keyboardDidShow: (NSNotification *)notif 
{
	if (displayKeyboard) {
		return;
	}	
	
	if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || 
		self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) 
	{
		m_scrollView.frame = CGRectMake(0, 0, SCROLLVIEW_CONTENT_WIDTH_LANDSCAPE, 140);
	}
	else 
	{
		m_scrollView.frame = CGRectMake(0, 0, SCROLLVIEW_CONTENT_WIDTH_PORTRAIT, 240);
	}
	
	CGRect textFieldRect = [m_activeField frame];
	textFieldRect.origin.y += 10;
	[m_scrollView scrollRectToVisible:textFieldRect animated:YES];

	displayKeyboard = YES;
}

- (void) keyboardDidHide: (NSNotification *)notif 
{
	if (!displayKeyboard) {
		return; 
	}
	
	if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || 
		self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) 
	{
		m_scrollView.frame = CGRectMake(0, 0, SCROLLVIEW_CONTENT_WIDTH_LANDSCAPE, 300);
		m_scrollView.contentSize = CGSizeMake(SCROLLVIEW_CONTENT_WIDTH_LANDSCAPE, SCROLLVIEW_CONTENT_HEIGHT_LANDSCAPE);
	}
	else
	{
		m_scrollView.frame = CGRectMake(0, 0, SCROLLVIEW_CONTENT_WIDTH_PORTRAIT, 460);
		m_scrollView.contentSize = CGSizeMake(SCROLLVIEW_CONTENT_WIDTH_PORTRAIT, SCROLLVIEW_CONTENT_HEIGHT_PORTRAIT);
	}
		
	displayKeyboard = NO;	
}

iPhone 画图

MyDrawView file:

#import <UIKit/UIKit.h>


@interface MyDrawView : UIView {
	CGPoint		firstTouch; 
	CGPoint		lastTouch; 
	UIImage		*drawImage;
	CGRect		redrawRect;	
}

@property CGPoint firstTouch; 
@property CGPoint lastTouch; 
@property (nonatomic, retain) UIImage *drawImage;
@property (readonly) CGRect currentRect;
@property CGRect redrawRect;

@end

-------------------------------------
#import "MyDrawView.h"


@implementation MyDrawView

@synthesize firstTouch; 
@synthesize lastTouch; 
@synthesize drawImage; 
@synthesize redrawRect;
@synthesize currentRect;

-(CGRect)currentRect
{
	return CGRectMake((firstTouch.x > lastTouch.x) ? lastTouch.x : firstTouch.x, 
					  (firstTouch.y > lastTouch.y) ? lastTouch.y : firstTouch.y, 
					  fabsf(firstTouch.x - lastTouch.x), 
					  fabsf(firstTouch.y - lastTouch.y));	
}

- (id)initWithCoder:(NSCoder*)coder 
{
	if (( self = [super initWithCoder:coder] )) 
	{ 		
		if (drawImage == nil)
		{
			self.drawImage = [UIImage imageNamed:@"green_circle.png"];
		}
	}
	return self;	
}

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    // Drawing code
	CGFloat horizontalOffset = drawImage.size.width / 2; 
	CGFloat verticalOffset = drawImage.size.height / 2; 
	CGPoint drawPoint = CGPointMake(lastTouch.x - horizontalOffset, lastTouch.y - verticalOffset);
	[drawImage drawAtPoint:drawPoint];
}

- (void)dealloc {
	[drawImage release];	
    [super dealloc];
}

#pragma mark -
#pragma mark UI Touches
#pragma mark -
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 	
	UITouch *touch = [touches anyObject]; 
	firstTouch = [touch locationInView:self]; 
	lastTouch = [touch locationInView:self];
	[self setNeedsDisplay];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{
	UITouch *touch = [touches anyObject]; 
	lastTouch = [touch locationInView:self];
	//[self setNeedsDisplay];
	
		CGFloat horizontalOffset = drawImage.size.width / 2; 
		CGFloat verticalOffset = drawImage.size.height / 2; 
		redrawRect = CGRectUnion(redrawRect, CGRectMake(lastTouch.x - horizontalOffset, 
														lastTouch.y - verticalOffset, 
														drawImage.size.width, 
														drawImage.size.height));	
	
	redrawRect = CGRectInset(redrawRect, -2.0, -2.0); 
	[self setNeedsDisplayInRect:redrawRect];
}

@end

----------------------------
MyDrawViewController

@interface MyDrawViewController : UIViewController {
	UIImageView *m_myImage;
}

@property(nonatomic,retain) IBOutlet UIImageView *m_myImage;

@end

------------
.m file:
...
- (void)viewDidLoad {
    [super viewDidLoad];
	
	CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 480.0f);
	m_myImage = [[UIImageView alloc] initWithFrame:myImageRect];
	[m_myImage setImage:[UIImage imageNamed:@"Background.png"]];
	m_myImage.opaque = YES; // explicitly opaque for performance
	[self.view addSubview:m_myImage];
}

iPhone UITableView委托

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 0;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}

/*
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44.0f;
}
*/

iPhone 从视图中删除所有子视图

for (int i = 0; i < [[self.view subviews] count]; i++ ) {
    [[[self.view subviews] objectAtIndex:i] removeFromSuperview];
}

iPhone 检测UINavigationController上的后退按钮触摸

-(void) viewWillDisappear:(BOOL)animated {
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
       // back button was pressed.  We know this is true because self is no longer
       // in the navigation stack.  
    }
    [super viewWillDisappear:animated];
}

iPhone 带有Opengl coverflow的COCOS2D

#import "HelloWorldScene.h"
#import "MenuScene.h"
#import "Common.h"
#import "GameScene.h"

UIWindow *flowCoverWindow;
UIView *flowCoverView;

NSString *currentImage;
NSString *previousImage;

#define kImageTag 0x01

@implementation FlowCoverViewController
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
			(interfaceOrientation == UIInterfaceOrientationLandscapeRight));
}
- (int)flowCoverNumberImages:(FlowCoverView *)view
{
	return 6;
}
- (IBAction)done:(id)sender
{
	NSLog(@"done");

	[[self parentViewController] dismissModalViewControllerAnimated:YES];
	[[Director sharedDirector] resume];
}
- (UIImage *)flowCover:(FlowCoverView *)view cover:(int)image
{
	switch (image) {
		case 0:
		default:

			return [UIImage imageNamed:@"dButton1.png"];
		case 1:
			return [UIImage imageNamed:@"dButton2.png"];
		case 2:
			return [UIImage imageNamed:@"dButton3.png"];
		case 3:
			return [UIImage imageNamed:@"dButton4.png"];
		case 4:
			return [UIImage imageNamed:@"dButton5.png"];
		case 5:
			return [UIImage imageNamed:@"dButton6.png"];

	}
}

- (void)flowCover:(FlowCoverView *)view didSelect:(int)image
{
	NSLog(@"Selected Index %d",image);

	[[self parentViewController] dismissModalViewControllerAnimated:YES];
	[[Director sharedDirector] resume];
	[[[Director sharedDirector] openGLView] removeFromSuperview];

	currentTerrain = image;

	Scene *s2 = [Scene node];
	[s2 addChild: [LevelSelectionLayer node]];
	[[Director sharedDirector] replaceScene: s2];

}

@end

// HelloWorld implementation
@implementation HelloWorld

+(id) scene
{
	// 'scene' is an autorelease object.
	Scene *scene = [Scene node];

	// 'layer' is an autorelease object.
	HelloWorld *layer = [HelloWorld node];

	// add layer as a child to scene
	[scene addChild: layer];

	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
-(id) init
{

	if( (self=[super init] )) {

			}

	[self ShowCoverFlow];
	currentImage = @"icon.png";
	previousImage = @"f";
	testImage = [Sprite spriteWithFile:currentImage ];

	[testImage setPosition:ccp(60,70)];
	//[self addChild:testImage z:1 tag:kImageTag];
	[self schedule: @selector(UpdateImage:) interval:1/60.0f];
	[self MoveImage];
	return self;

}
-(void)MoveImage {

	id moveSpriteCW = [RotateBy actionWithDuration:3  angle:360];
	id moveSpriteCCW = [RotateBy actionWithDuration:1  angle:180];
	id seq1 = [Sequence actions: moveSpriteCW, moveSpriteCCW, nil];
	id seq2 = [seq1 reverse];
	[testImage runAction: [Sequence actions: seq1, seq2, nil]];

}
-(void)UpdateImage:(id) sender{
	NSLog(@"currentImage is = %@", currentImage);

}
-(void) ShowCoverFlow
{

	UINavigationController *testViewController;
	FlowCoverViewController *flowCover;
	flowCoverView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; 

	//using a navigation controller to present FlowCover without it rotating to portrait
	testViewController = [[UINavigationController alloc] init];

	//The navigation controller will try to put a nav bar in the window, so we hide it
	[testViewController setNavigationBarHidden:YES animated:NO];

	[testViewController setView:flowCoverView];

	NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"TestFC" owner:self options:nil];
	flowCover = [array objectAtIndex:0];

	testViewController.delegate = self;
    [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
	[[[Director sharedDirector] openGLView] addSubview:flowCoverView];
	[[Director sharedDirector] pause];
	[testViewController presentModalViewController:flowCover animated:YES];

 }

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{

	[super dealloc];
}
@end

iPhone 拍摄屏幕快照

UIGraphicsBeginImageContext(webview.frame.size);
	[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
	UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);

iPhone 轻松实现获取数据持久性的文档目录路径的功能

- (NSString *)documentsDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return documentsDirectory;
}

iPhone iPhone解天极??é??žUTF-8CS“XML

做iPhone的网络应用,处理XML是家常便饭,NSXMLParser用起来还是得心应手的。不过这个东西,处理非UTF-8,会解析失败。这篇文章就是想和大家一起分享一些这方面开发的新的。

 

       我们在某个RSS地址,可以得到下面这样的XML文件。我这里只是截取一段,

 

---------------------------------------


<?xml version="1.0" encoding="big5"?>

<rss version="2.0">

<channel>

<title>RTHK On Internet - 即 時 新 聞</title>

<link><![CDATA[http://www.rthk.org.hk/rthk/news/expressnews/]]></link>

<description>RTHK On Internet - 即 時 新 聞</description>

<pubDate>Sun, 11 Oct 2009 15:02:02 +0800</pubDate>


<item>

<title><![CDATA[衞生署要求浸會醫院4周內 就產婦死亡個案提交報告   ]]></title>

<link><![CDATA[http://www.rthk.org.hk/rthk/news/expressnews/20091011/news_20091011_55_618483.htm]]></link>

<description><![CDATA[

衞生署昨晚已經收到浸會醫院通知,有一宗產婦死亡個案,浸會醫院需要在4星期內向衞生署提交報告,案件亦交由死因庭跟進。

 

 

 

衞生署數字顯示,由07年至今年8月,共接獲97宗私家醫院醫療事故的通報。去年發生的事故中,最多的是進行手術或介入程序期間出現併發症,其次還有孕婦及產婦死亡,或與孕婦在分娩過程中,生產時,或產後出現嚴重併發症;部份則包括初生嬰兒出現死亡或嚴重受傷;錯誤為病人或身體部位進行外科或介入手術程序等。

 

 

]]></description>

<pubDate>

Sun, 11 Oct 2009 14:50:46 +0800

</pubDate>

</item>


</channel>

</rss>

----------------------------------------

这是一个很常用的RSS返回的XML,是繁体中文的,编码格式是big5。说编码格式是big5有两层意思:

[1] 网络流返回的NSData是big5编码的。所以这样的NSData送给NSXMLParser是不能正确解析的。

[2] 第一句话指明了XML文件也是用big5编码的。

 

对应于上面两个问题,我的解决思路是:

[1] 把Big5编码的NSData转换成UTF-8编码的NSData

[2] 将第一行<?xml version="1.0" encoding="big5"?>转换成<?xml version="1.0" encoding="utf-8"?>

 

第二个转换不难,只要我们有NSString对象。第一个转换要用到CFStringRef,代码如下:


Cpp代码 
CFStringRef big5Str = CFStringCreateWithBytes(NULL,   
                                    [inData bytes],   
                                    [inData length],   
                                    kCFStringEncodingBig5_HKSCS_1999,   
                                    false); //[A]   
if (NULL == big5Str) {   
        return nil;   
}   
else {   
    NSString *big5NSString = (NSString *)big5Str;   
    NSString *utf8NSString = [big5NSString stringByReplacingOccurrencesOfString:@"<?xml version=\"1.0\" encoding=\"big5\"?>"    
                           withString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"]; //[B]   
    return [utf8NSString dataUsingEncoding:NSUTF8StringEncoding]; //[C]   
}  

CFStringRef big5Str = CFStringCreateWithBytes(NULL,
									[inData bytes],
									[inData length],
									kCFStringEncodingBig5_HKSCS_1999,
									false); //[A]
if (NULL == big5Str) {
        return nil;
}
else {
	NSString *big5NSString = (NSString *)big5Str;
	NSString *utf8NSString = [big5NSString stringByReplacingOccurrencesOfString:@"<?xml version=\"1.0\" encoding=\"big5\"?>" 
						   withString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"]; //[B]
	return [utf8NSString dataUsingEncoding:NSUTF8StringEncoding]; //[C]
} 思路就是先把NSData转成CFStringRef的对象[A], 然后这个对象再转成UTF-8的NSData [C],这就解决了问题[1]

中间的[B]就解决了问题[2]。这里要注意两个问题:

(1)如果你的XML编码是GBK,或者GB23120或者其他的,kCFStringEncodingBig5_HKSCS_1999要换成你对应的编码方式。

(2)如果你的XML编码也是big5的,也许kCFStringEncodingBig5_HKSCS_1999并不适合你的应用。因为对应big5的编码常量还有两种,他们是:

kCFStringEncodingBig5_E

kCFStringEncodingBig5。

这个你可以查阅帮助文档,然后一个个试。

 

然后把return的NSData送到NSXMLParser,就可以正确解析了。可是还没有结束,大家仔细看看XML文件里面还有&#34910这样的东西。这个是繁体中文”衛“字,我们如果不处理这个东西,显示给用户看得就是&#34910,这显然是不行的。这个其实也好办,只需要用下面这句话就可以把一个number转成NSString了:


[NSString stringWithFormat:@"%C", number]

这个number就是34910,是一个整数,十进制的整数(不是十六进制的)。到这里,整个处理过程就OK了,我们就可以正确得到Big5的RSS新闻了。因为这是一个客户项目,不过我可以给各小截图大家看看:

iPhone 从您的代码启动Safari

[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://www.google.co.uk"]];