您的位置:首页 > 其它

iphone开发笔记---1(转载)

2011-05-12 17:32 375 查看
iphone开发笔记

退回输入键盘
- (BOOL) textFieldShouldReturn:(id)textField{
[textField resignFirstResponder];
}

CGRect
CGRect frame = CGRectMake (origin.x, origin.y, size.width, size.height);矩形
NSStringFromCGRect(someCG) 把CGRect结构转变为格式化字符串;
CGRectFromString(aString) 由字符串恢复出矩形;
CGRectInset(aRect) 创建较小或较大的矩形(中心点相同),+较小 -较大
CGRectIntersectsRect(rect1, rect2) 判断两矩形是否交叉,是否重叠
CGRectZero 高度和宽度为零的/位于(0,0)的矩形常量

CGPoint & CGSize
CGPoint aPoint = CGPointMake(x, y);
CGSize aSize = CGSizeMake(width, height);

设置透明度
[myView setAlpha:value]; (0.0 < value < 1.0)

设置背景色
[myView setBackgroundColor:[UIColor redColor]];
(blackColor;darkGrayColor;lightGrayColor;
whiteColor;grayColor; redColor; greenColor;
blueColor; cyanColor;yellowColor;
magentaColor;orangeColor;purpleColor;
brownColor; clearColor; )

自定义颜色
UIColor *newColor = [[UIColor alloc]
initWithRed:(float) green:(float) blue:(float) alpha:(float)];
0.0~1.0

竖屏
320X480

横屏
480X320

状态栏高
20 像素

导航栏、工具栏高
44像素

隐藏状态栏
[[UIApplication shareApplication] setStatusBarHidden: YES animated:NO]

横屏
[[UIApplication shareApplication]
setStatusBarOrientation:UIInterfaceOrientationLandscapeRight].

屏幕变动检测
orientation == UIInterfaceOrientationLandscapeLeft

全屏
window=[[UIWindow alloc] initWithFrame:[UIScreen mainScreen] bounds];

自动适应父视图大小:
aView.autoresizingSubviews = YES;
aView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight);

定义按钮
UIButton *scaleUpButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[scaleUpButton setTitle:@"放 大" forState:UIControlStateNormal];
scaleUpButton.frame = CGRectMake(40, 420, 100, 40);
[scaleUpButton addTarget:self
action:@selector(scaleUp)
forControlEvents:UIControlEventTouchUpInside];

设置视图背景图片
UIImageView *aView;
[aView setImage:[UIImage imageNamed:@”name.png”]];
view1.backgroundColor = [UIColor colorWithPatternImage:
[UIImage imageNamed:@"image1.png"]];

UISlider *slider = (UISlider *) sender;
NSString *newText = [[NSString alloc] initWithFormat:@”%d”, (int)(slider.value + 0.5f)];
label.text = newText;

活动表单
<UIActionSheetDelegate>

- (IBActive) someButtonPressed:(id) sender
{
UIActionSheet *actionSheet = [[UIActionSheet alloc]
initWithTitle:@”Are you sure?”
delegate:self
cancelButtonTitle:@”No way!”
destructiveButtonTitle:@”Yes, I’m Sure!”
otherButtonTitles:nil];
[actionSheet showInView:self.view];
[actionSheet release];
}

警告视图
<UIAlertViewDelegate>

- (void) actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger) buttonIndex
{
if(buttonIndex != [actionSheet cancelButtonIndex])
{
NSString *message = [[NSString alloc] initWithFormat:@”You can
breathe easy, everything went OK.”];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@”Something was done”
message:message
delegate:self
cancelButtonTitle:@”OK”
otherButtonTitles:nil];
[alert show];
[alert release];
[message release];
}
}

动画效果
-(void)doChange:(id)sender
{
if(view2 == nil)
{
[self loadSec];
}
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:([view1 superview]?UIViewAnimationTransitionFlipFromLeft:UIViewAnimationTransitionFlipFromRight)forView:self.view cache:YES];

if([view1 superview]!= nil)
{
[view1 removeFromSuperview];
[self.view addSubview:view2];

}else {

[view2 removeFromSuperview];
[self.view addSubview:view1];
}
[UIView commitAnimations];
}

Table View <UITableViewDateSource>
#pragma mark -
#pragma mark Table View Data Source Methods
//指定分区中的行数,默认为1
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}

//设置每一行cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIndentifier = @"SimpleTableIndentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIndentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:SimpleTableIndentifier]
autorelease];
}
UIImage *image = [UIImage imageNamed:@"13.gif"];
cell.imageView.image = image;

NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
cell.textLabel.font = [UIFont boldSystemFontOfSize:20];

if(row < 5)
cell.detailTextLabel.text = @"Best friends";
else
cell.detailTextLabel.text = @"friends";
return cell;
}

图像、文本标签和详细文本标签

图像:如果设置图像,则它显示在文本的左侧; 文本标签:这是单元的主要文本(UITableViewCellStyleDefault 只显示文本标签);详细文本标签:这是单元的辅助文本,通常用作解释性说明或标签

UITableViewCellStyleSubtitle
UITableViewCellStyleDefault
UITableViewCellStyleValue1
UITableViewCellStyleValue2

<UITableViewDelegate>
#pragma mark -
#pragma mark Table View Delegate Methods
//把每一行缩进级别设置为其行号
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
return row;
}
//获取传递过来的indexPath值
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
if (row == 0)
return nil;
return indexPath;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
NSString *rowValue = [listData objectAtIndex:row];
NSString *message = [[NSString alloc] initWithFormat:@"You selected %@",rowValue];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Row Selected"
message:message
delegate:nil
cancelButtonTitle:@"Yes, I did!"
otherButtonTitles:nil];
[alert show];
[alert release];
[message release];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//设置行的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40;
}

NavigationController 推出push 推出pop
[self.navigationController pushViewController:_detailController animated:YES];
[self.navigationController popViewControllerAnimated:YES];

Debug:
NSLog(@"%s %d", __FUNCTION__, __LINE__);

纯代码时,点击textField外的地方回收键盘:
先定义一个UIControl类型的对象,在上面可以添加触发事件,令SEL实践为回收键盘的方法,最后将UIControl的实例加到当前View上。
UIControl *m_control = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[m_control addTarget:self action:@selector(keyboardReturn)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:m_control];

- (void) keyboardReturn
{
[aTextField resignFirstResponder];
}

调整输入界面
当键盘调出时将输入框覆盖时,可以用下方法:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
[self.view setFrame:CGRectMake(0, -100, 320, 480) ];
return YES;
}
当准备输入时,将视图的位置上调100,这样键盘就不能覆盖到输入框。

当依赖注入方法不好使时,可以在AppDelegate内申明一个全局的控制器实例_anotherViewController,在另一个需要使用_anotherViewController的地方定义以下委托方法,使用共享的UIApplication实例来获取该委托的引用
SomeAppDelegate *appDelegate = (SomeAppDelegate *)[[UIApplication sharedApplication] delegate];
_anotherViewController = appDelegate._anotherViewController;

UIViewController内建Table View

纯代码在UIViewController控制器内建Table View
@interface RootViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
NSArray *timeZoneNames;
}
@property (nonatomic,retain) NSArray *timeZoneNames;
@end

(void) loadView
{
UITableView *tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] style: UITableViewStylePlain];
tableView.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingWidth);
tableView.delegate = self;
tableView.dataSource = self;
[tableView reloadData];

self.view = tableView;
[tableView release];
}

将plist文件中的数据赋给数组
NSString *thePath = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:thePath];

UITouch
手指的触摸范围:64X64

#pragma mark -
#pragma mark Touch Events

- (void)touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event {
originFrame = bookCover.frame;
NSLog(@"%s %d", __FUNCTION__,__LINE__);

if ([touches count] == 2)
{
NSArray *twoTouches = [touches allObjects];
UITouch *firstTouch = [twoTouches objectAtIndex:0];
UITouch *secondTouch = [twoTouches objectAtIndex:1];
CGPoint firstPoint = [firstTouch locationInView:bookCover];
CGPoint secondPoint = [secondTouch locationInView:bookCover];

CGFloat deltaX = secondPoint.x - firstPoint.x;
CGFloat deltaY = secondPoint.y - firstPoint.y;
initialDistance = sqrt(deltaX * deltaX + deltaY * deltaY );
frameX = bookCover.frame.origin.x;
frameY = bookCover.frame.origin.y;
frameW = bookCover.frame.size.width;
frameH = bookCover.frame.size.height;
NSLog(@"%s %d", __FUNCTION__,__LINE__);
}
}

- (void)touchesMoved:(NSSet *) touches withEvent:(UIEvent *) event {

if([touches count] == 2)
{
NSLog(@"%s %d", __FUNCTION__,__LINE__);

NSArray *twoTouches = [touches allObjects];
UITouch *firstTouch = [twoTouches objectAtIndex:0];
UITouch *secondTouch = [twoTouches objectAtIndex:1];

CGPoint firstPoint = [firstTouch locationInView:bookCover];
CGPoint secondPoint = [secondTouch locationInView:bookCover];

CGFloat deltaX = secondPoint.x - firstPoint.x;
CGFloat deltaY = secondPoint.y - firstPoint.y;
CGFloat currentDistance = sqrt(deltaX * deltaX + deltaY * deltaY );

if (initialDistance == 0) {
initialDistance = currentDistance;
}
else if (currentDistance != initialDistance)
{
CGFloat changedDistance = currentDistance - initialDistance;
NSLog(@"changedDistance = %f",changedDistance);
[bookCover setFrame:CGRectMake(frameX - changedDistance / 2,
frameY - (changedDistance * frameH) / (2 * frameW),
frameW + changedDistance,
frameH + (changedDistance * frameH) / frameW)];
}
}
}

- (void)touchesEnded:(NSSet *) touches withEvent:(UIEvent *) event {
UITouch *touch = [touches anyObject];

//双击图片变大/还原
if ([touch tapCount] == 2)
{
NSLog(@"%s %d", __FUNCTION__,__LINE__);

if (!flag) {
[bookCover setFrame:CGRectMake(bookCover.frame.origin.x - bookCover.frame.size.width / 2,
bookCover.frame.origin.y - bookCover.frame.size.height / 2,
2 * bookCover.frame.size.width,
2 * bookCover.frame.size.height)];
flag = YES;
}
else {
[bookCover setFrame:CGRectMake(bookCover.frame.origin.x + bookCover.frame.size.width / 4, bookCover.frame.origin.y + bookCover.frame.size.height / 4,
bookCover.frame.size.width / 2, bookCover.frame.size.height / 2)];
flag = NO;
}
}
}

Get the Location of Touches
(CGPoint)locationInView:(UIView *)view
(CGPoint)previousLocationInView:(UIView *)view
view window

Getting Touch Attributes
tapCount(read only) timestamp(read only) phase(read only)

Getting a Touch Object's Gesture Recognizers
gestureRecognizers

Touch Phase
UITouchPhaseBegan
UITouchPhaseMoved
UITouchPhaseStationary
UITouchPhaseEnded
UITouchPhaseCancelled

从Plist里读内容
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
NSString *book = [dictionary objectForKey:bookTitle];
[textView setText:book];

(void) initialize {
NSUserDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"YES" forKey:@"DeleteBackup"];
[defaults registerDefaults:appDefaults];
}

To get a value of a default, use the valueForKey: method:
[[theDefaultsController values] valueForKey:@"userName"];
To set a value for a default, use setValue:forKey:
[[theDefaultsController values] setValue:newUserName forKey:@"userName"];

[[NSUserDefaults standardUserDefaults] setValue:aVale forKey:aKey];
[[NSUserDefaults standardUserDefaults] valueForKey:aKey];

获取Documents目录
NSArray *paths = NSSearchPathForDictionariesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename = [documentsDirectory
stringByAppendingPathComponent:@"theFile.txt"];

获取tmp目录
NSString *tempPath = NSTemporaryDirectory();
NSString *tempFile = [tempPath stringByAppendingPathComponent:@"tempFile.txt"];

[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"someKey"];
[[NSUserDefaults standardUserDefaults] objectForKey:aKey];

自定义NavigationBar
navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[navigationBar setBarStyle:UIBarStyleBlackOpaque];

myNavigationItem = [[UINavigationItem alloc] initWithTitle:@"Setting"];
[navigationBar setItems:[NSArray arrayWithObject:myNavigationItem]];
[self.view addSubview:navigationBar];

backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
myNavigationItem.leftBarButtonItem = backButton;

利用Safari打开一个链接
NSURL *url = [NSURL URLWithString:@"http://www.cnblogs.com/tracy-e/"];
[[UIApplication sharedApplication] openURL:url];

利用UIWebView显示pdf文件、网页。。。
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[webView setDelegate:self];
[webView setScalesPageToFit:YES];
[webView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[webView setAllowsInlineMediaPlayback:YES];
[self.view addSubview:webView];
NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"ojc" ofType:@"pdf"];
NSURL *url = [NSURL fileURLWithPath:pdfPath];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:5];
[webView loadRequest:request];

[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL
URLWithString: @"http://www.cnblogs.com/tracy-e/"]]];

NSString *errorString = [NSString stringWithFormat:@"<html><center><font size=
+5 color ='red'>An Error Occurred:<br>%@</fone></center></html>",error];
[myWebView loadHTMLString:errorString baseURL:nil];

//Stopping a load request when the view is to disappear
- (void)viewWillDisappear:(BOOL)animate{
if ([myWebView loading]){
[myWebView stopLoading];
}
myWebView.delegate = nil;
[UIApplication shareApplication].networkActivityIndicatorVisible = NO;
}

汉字转码
NSString *oriString = @"\u67aa\u738b";
NSString *escapedString = [oriString
stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

Checking for background support on earlier versions of iOS
UIDevice *device = [UIDevice currentDevice];
BOOL backgroundSupported = NO;
if ([device respondsToSelector:@selector(isMultitaskingSupported)]){
backgroundSupported = device.multitaskingSupported;
}

Being a Responsible,Multitasking-Aware Application
# Do not make any OpenGL ES calls from your code.
# Cancel any Bonjour-related services before being suspended.
# Be prepared to handle connection failures in your network-based sockets.
# Save your application state before moving to the background.
# Release any unneeded memory when moving to the background.
# Stop using shared system resources before being suspended.
# Avoid updating your windows and views.
# Respond to connect and disconnect notification for external accessories.
# Clean up resource for active alerts when moving to the background.
# Remove sensitive information from views before moving to the background.
# Do minimal work while running in the background.

Handing the Keyboard notifications
//Call this method somewhere in your view controller setup code
- (void) registerForKeyboardNotifications{

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasHidden:)
name:UIKeyboardDidHideNotification
object:nil];

}

//Called when the UIKeyboardDidShowNotification is sent
- (void)keyboardWasShown:(NSNotification *) aNotification{
if(keyboardShown)
return;
NSDictionary *info = [aNotification userInfo];

//get the size of the keyboard.
NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;

//Resize the scroll view
CGRect viewFrame = [scrollView frame];
viewFrame.size.height -= keyboardSize.height;

//Scroll the active text field into view
CGRect textFieldRect = [activeField frame];
[scrollView scrollRectToVisible:textFieldRect animated:YES];

keyboardShown = YES;
}

//Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification *) aNotification{
NSDictionary *info = [aNotification userInfo];

//Get the size of the keyboard.
NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;

//Reset the height of the scroll view to its original value
CGRect viewFrame = [scrollView Frame];
viewFrame.size.height += keyboardSize.height;
scrollView.frame = viewFrame;

keyboardShown = NO;
}

点击键盘的next按钮,在不同的textField之间换行
//首先给不同的textField赋不同的且相邻的tag值
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if ([textField returnKeyType] != UIReturnKeyDone)
{
NSInteger nextTag = [textField tag] + 1;
UIView *nextTextField = [[self tableView] viewWithTag:nextTag];
[nextTextField becomeFirstResponder];
}
else {
[textField resignFirstResponder];
}
return YES;
}

Configuring a date formatter
- (void)viewDidLoad {
[super viewDidLoad];
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setGeneratesCalendarDates:YES];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setCalendar:[NSCalendar autoupdatingCurrentCalendar]];
[dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
DOB.placeholder = [NSString stringWithFormat:@"Example: %@",[dateFormatter stringFromDate:[NSDate date]]];
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
[textField resignFirstResponder];
if ([textField.text isEqualToString:@""])
return;
switch (textField.tag){
case DOBField:
NSDate *theDate = [dateFormatter dateFromString:textField.text];
if (theDate)
[inputDate setObject:theDate forKey:MyAppPersonDOBKey];
break;
default:
break;
}
}

tableView的cell高度

tableView的cell高度除了在delegate中指定外,还可以在任意位置以[tableView setRowHeight:44]的方式指定

[[self navigationItem] setLeftBarButtonItem:[self editButtonItem]];

- (void)setEditing:(BOOL)editing animated:(BOOL)animated{
[super setEditing:editing animated:animated];
if (editing){
......
}
else{
......
}
}

One added a subview to a view, release the subview to avoid the extra retain count of it, Because when you insert a view as a subview using addSubview:, the subview is retained by its superview. When you remove the subview from its superview using the removeFromSuperview: method, subview is autoreleased.

为UINavigationBar设置背景图片
在iPhone开发中, 有时候我们想给导航条添加背景图片, 实现多样化的导航条效果, 用其他方法往往无法达到理想的效果, 经过网上搜索及多次实验, 确定如下最佳实现方案:
为UINavigatonBar增加如下Category:

@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed: @"NavigationBar.png"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

例如, 在我的项目中, 添加如下代码:
/////////////////////////////////////////////////////////
/* input: The image and a tag to later identify the view */
@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed: @"title_bg.png"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end
/////////////////////////////////////////////////////////
@implementation FriendsPageViewController
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
self.navigationBar.tintColor = [UIColor purpleColor];

[self initWithRootViewController:[[RegPageViewController alloc] init]];
[super viewDidLoad];
}
......
实现的效果如下图:



转载,原文地址 http://blog.csdn.net/wave_1102/archive/2009/11/04/4768212.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: