iphone开发常用代码
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:[UIColorredColor]];
(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:[UIScreenmainScreen] bounds];
自动适应父视图大小:
aView.autoresizingSubviews = YES;
aView.autoresizingMask =(UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight);
定义按钮
UIButton *scaleUpButton = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
[scaleUpButton setTitle:@"放 大" forState:UIControlStateNormal];
scaleUpButton.frame = CGRectMake(40, 420,100, 40);
[scaleUpButton addTarget:self
action:@selector(scaleUp)
forControlEvents:UIControlEventTouchUpInside];
设置视图背景图片
UIImageView *aView;
[aView setImage:[UIImageimageNamed:@”name.png”]];
view1.backgroundColor = [UIColorcolorWithPatternImage:
[UIImageimageNamed:@"image1.png"]];
自定义UISlider的样式和滑块
我们使用的是UISlider的setMinimumTrackImage,和setMaximumTrackImage方法来定义图片的,这两个方法可以设置滑块左边和右边的图片的,不过如果用的是同一张图片且宽度和控件宽度基本一致,就不会有变形拉伸的后果,先看代码,写在 viewDidLoad中:
//左右轨的图片
UIImage *stetchLeftTrack= [UIImageimageNamed:@"brightness_bar.png"];
UIImage *stetchRightTrack = [UIImageimageNamed:@"brightness_bar.png"];
//滑块图片
UIImage *thumbImage = [UIImage imageNamed:@"mark.png"];
UISlider *sliderA=[[UISlider alloc]initWithFrame:CGRectMake(30, 320,257, 7)];
sliderA.backgroundColor = [UIColor clearColor];
sliderA.value=1.0;
sliderA.minimumValue=0.7;
sliderA.maximumValue=1.0;
[sliderA setMinimumTrackImage:stetchLeftTrackforState:UIControlStateNormal];
[sliderA setMaximumTrackImage:stetchRightTrackforState:UIControlStateNormal];
//注意这里要加UIControlStateHightlighted的状态,否则当拖动滑块时滑块将变成原生的控件
[sliderA setThumbImage:thumbImage forState:UIControlStateHighlighted];
[sliderA setThumbImage:thumbImage forState:UIControlStateNormal];
//滑块拖动时的事件
[sliderA addTarget:self action:@selector(sliderValueChanged:)forControlEvents:UIControlEventValueChanged];
//滑动拖动后的事件
[sliderA addTarget:self action:@selector(sliderDragUp:)forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sliderA];
为了大家实验方便,我附上背景图brightness_bar.png和滑块图mark.png
-(IBAction)sliderValueChanged:(id)sender{UISlider *slider = (UISlider *) sender;
NSString *newText = [[NSString alloc]initWithFormat:@”%d”, (int)(slider.value + 0.5f)];
label.text = newText;
}
活动表单
<UIActi*****heetDelegate>
- (IBActive) someButtonPressed:(id)sender
{
UIActi*****heet *acti*****heet =[[UIActi*****heet alloc]
initWithTitle:@”Are you sure?”
delegate:self
cancelButtonTitle:@”No way!”
destructiveButtonTitle:@”Yes, I’m Sure!”
otherButtonTitles:nil];
[acti*****heetshowInView:self.view];
[acti*****heet release];
}
警告视图
<UIAlertViewDelegate>
- (void) acti*****heet:(UIActi*****heet *)acti*****heetdidDismissWithButtonIndex:(NSInteger) buttonIndex
{
if(buttonIndex !=[acti*****heet 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];
[alertshow];
[alertrelease];
[messagerelease];
}
}
动画效果
-(void)doChange:(id)sender
{
if(view2 == nil)
{
[self loadSec];
}
[UIView beginAnimati*****:nil context:NULL];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:([view1superview]?UIViewAnimationTransitionFlipFromLeft:UIViewAnimationTransitionFlipFromRight)forView:self.viewcache:YES];
if([view1 superview]!= nil)
{
[view1 removeFromSuperview];
[self.view addSubview:view2];
}else {
[view2 removeFromSuperview];
[self.view addSubview:view1];
}
[UIView commitAnimati*****];
}
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 = [tableViewdequeueReusableCellWithIdentifier: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 = [listDataobjectAtIndex:row];
cell.textLabel.font =[UIFont boldSystemFontOfSize:20];
if(row < 5)
cell.detailTextLabel.text = @"Bestfriends";
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 *)tableViewdidSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
NSString *rowValue = [listDataobjectAtIndex:row];
NSString *message = [[NSString alloc]initWithFormat:@"You selected %@",rowValue];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Row Selected"
message:message
delegate:nil
cancelButtonTitle:@"Yes, Idid!"
otherButtonTitles:nil];
[alert show];
[alert release];
[message release];
[tableView deselectRowAtIndexPath:indexPathanimated:YES];
}
//设置行的高度
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40;
}
NavigationController 推出push 推出pop
[self.navigationControllerpushViewController:_detailController animated:YES];
[self.navigationControllerpopViewControllerAnimated: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:selfaction:@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;
}
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
[self.view setFrame:CGRectMake(0, 0, 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 = [[UITableViewalloc] 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 = [NSArrayarrayWithContentsOfFile:thePath];
UITouch
手指的触摸范围:64X64
#pragma mark -
#pragma mark Touch Events
- (void)touchesBegan:(NSSet *) toucheswithEvent:(UIEvent *) event {
originFrame = bookCover.frame;
NSLog(@"%s %d",__FUNCTION__,__LINE__);
if ([touches count] == 2)
{
NSArray *twoTouches = [touches allObjects];
UITouch *firstTouch = [twoTouchesobjectAtIndex:0];
UITouch *secondTouch = [twoTouchesobjectAtIndex:1];
CGPoint firstPoint = [firstTouchlocationInView:bookCover];
CGPoint secondPoint = [secondTouchlocationInView: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 *) toucheswithEvent:(UIEvent *) event {
if([touches count] == 2)
{
NSLog(@"%s %d",__FUNCTION__,__LINE__);
NSArray *twoTouches = [touches allObjects];
UITouch *firstTouch = [twoTouchesobjectAtIndex:0];
UITouch *secondTouch = [twoTouchesobjectAtIndex:1];
CGPoint firstPoint = [firstTouchlocationInView:bookCover];
CGPoint secondPoint = [secondTouchlocationInView: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 *) toucheswithEvent:(UIEvent *) event {
UITouch *touch = [touches anyObject];
UITouch双击图片变大/还原
if ([touch tapCount] == 2)
{
NSLog(@"%s %d",__FUNCTION__,__LINE__);
if (!flag) {
[bookCoversetFrame: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 {
[bookCoversetFrame: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) times*****p(read only)phase(read only)
Getting a Touch Object's GestureRecognizers
gestureRecognizers
Touch Phase
UITouchPhaseBegan
UITouchPhaseMoved
UITouchPhaseStationary
UITouchPhaseEnded
UITouchPhaseCancelled
从Plist里读内容
NSString *plistPath = [[NSBundlemainBundle] pathForResource:@"book" ofType:@"plist"];
NSDictionary *dictionary = [[NSDictionaryalloc] initWithContentsOfFile:plistPath];
NSString *book = [dictionaryobjectForKey:bookTitle];
[textView setText:book];
(void) initialize {
NSUserDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionarydictionaryWithObject:@"YES" forKey:@"DeleteBackup"];
[defaults registerDefaults:appDefaults];
}
To get a value of a default, use thevalueForKey: method:
[[theDefaultsController values] valueForKey:@"userName"];
To set a value for a default, usesetValue: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 = [pathsobjectAtIndex:0];
NSString *filename = [documentsDirectory
stringByAppendingPathComponent:@"theFile.txt"];
获取tmp目录
NSString *tempPath =NSTemporaryDirectory();
NSString *tempFile = [tempPathstringByAppendingPathComponent:@"tempFile.txt"];
[[NSUserDefaults standardUserDefaults]setObject:data forKey:@"someKey"];
[[NSUserDefaults standardUserDefaults] objectForKey:aKey];
自定义NavigationBar
navigationBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
[navigationBarsetBarStyle:UIBarStyleBlackOpaque];
myNavigationItem = [[UINavigationItemalloc] initWithTitle:@"Setting"];
[navigationBar setItems:[NSArrayarrayWithObject:myNavigationItem]];
[self.view addSubview:navigationBar];
backButton = [[UIBarButtonItem alloc]initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:selfaction:@selector(back)];
myNavigationItem.leftBarButtonItem =backButton;
利用Safari打开一个链接
NSURL *url = [NSURLURLWithString:@"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];
[webViewsetAutoresizingMask:UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight];
[webView setAllowsInlineMediaPlayback:YES];
[self.view addSubview:webView];
NSString *pdfPath = [[NSBundle mainBundle]pathForResource:@"ojc" ofType:@"pdf"];
NSURL *url = [NSURLfileURLWithPath:pdfPath];
NSURLRequest *request = [NSURLRequestrequestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:5];
[webView loadRequest:request];
[myWebView loadRequest:[NSURLRequestrequestWithURL:[NSURL
URLWithString:@"http://www.cnblogs.com/tracy-e/"]]];
NSString *errorString = [NSStringstringWithFormat:@"<html><center><font size=
+5 color ='red'>An ErrorOccurred:<br>%@</fone></center></html>",error];
[myWebView loadHTMLString:errorStringbaseURL:nil];
//Stopping a load request when the view isto disappear
- (void)viewWillDisappear:(BOOL)animate{
if ([myWebView loading]){
[myWebView stopLoading];
}
myWebView.delegate = nil;
[UIApplicati*****hareApplication].networkActivityIndicatorVisible = NO;
}
汉字转码
NSString *oriString =@"\u67aa\u738b";
NSString *escapedString = [oriString
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Checking for background support on earlierversi***** of iOS
UIDevice *device = [UIDevicecurrentDevice];
BOOL backgroundSupported = NO;
if ([devicerespondsToSelector:@selector(isMultitaskingSupported)]){
backgroundSupported =device.multitaskingSupported;
}
Being a Resp*****ible,Multitasking-AwareApplication
# Do not make any OpenGL ES calls from yourcode.
# Cancel any Bonjour-related servicesbefore being suspended.
# Be prepared to handle connection failuresin your network-based sockets.
# Save your application state before movingto the background.
# Release any unneeded memory when movingto the background.
# Stop using shared system resources beforebeing suspended.
# Avoid updating your windows and views.
# Respond to connect and disconnectnotification for external accessories.
# Clean up resource for active alerts whenmoving to the background.
# Remove sensitive information from viewsbefore moving to the background.
# Do minimal work while running in thebackground.
Handing the Keyboard notificati*****
//Call this method somewhere in your viewcontroller setup code
- (void) registerForKeyboardNotificati*****{
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(keyboardWasHidden:)
name:UIKeyboardDidHideNotification
object:nil];
}
//Called when theUIKeyboardDidShowNotification is sent
- (void)keyboardWasShown:(NSNotification *)aNotification{
if(keyboardShown)
return;
NSDictionary *info = [aNotificationuserInfo];
//get the size of the keyboard.
NSValue *aValue = [infoobjectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [aValueCGRectValue].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];
[scrollViewscrollRectToVisible:textFieldRect animated:YES];
keyboardShown = YES;
}
//Called when theUIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification*) aNotification{
NSDictionary *info = [aNotificationuserInfo];
//Get the size of the keyboard.
NSValue *aValue = [infoobjectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValueCGRectValue].size;
//Reset the height of the scroll view toits 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:[NSLocalecurrentLocale]];
[dateFormatter setCalendar:[NSCalendarautoupdatingCurrentCalendar]];
[dateFormatter setTimeZone:[NSTimeZonedefaultTimeZone]];
[dateFormattersetDateStyle:NSDateFormatterShortStyle];
DOB.placeholder = [NSStringstringWithFormat:@"Example: %@",[dateFormatter stringFromDate:[NSDatedate]]];
}
- (void)textFieldDidEndEditing:(UITextField*)textField{
[textField resignFirstResponder];
if ([textField.textisEqualToString:@""])
return;
switch (textField.tag){
case DOBField:
NSDate *theDate = [dateFormatterdateFromString:textField.text];
if (theDate)
[inputDate setObject:theDateforKey:MyAppPersonDOBKey];
break;
default:
break;
}
}
tableView的cell高度
tableView的cell高度除了在delegate中指定外,还可以在任意位置以[tableView setRowHeight:44]的方式指定
[[self navigationItem]setLeftBarButtonItem:[self editButtonItem]];
- (void)setEditing:(BOOL)editinganimated:(BOOL)animated{
[super setEditing:editing animated:animated];
if (editing){
......
}
else{
......
}
}
One added a subview to a view, release thesubview to avoid the extra retain count of it, Because when you insert a viewas a subview using addSubview:, the subview is retained by its superview. When youremove 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
为UINavigationBar添加自定义背景
@implementation UINavigationBar(UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
//颜色填充
// UIColor *color = [UIColor redColor];
// CGContextRef context = UIGraphicsGetCurrentContext();
// CGContextSetFillColor(context, CGColorGetComponents( [colorCGColor]));
// CGContextFillRect(context, rect);
// self.tintColor = color;
//图片填充
UIColor *color= [UIColor colorWithRed:46.0f/255.0f
green:87.0f/255.0fblue:29.0f/255.0f alpha:1.0f];
UIImage *img = [UIImageimageNamed: @"bg.png"];
[img drawInRect:CGRectMake(0, 0, self.frame.size.width,self.frame.size.height)];
self.tintColor = color;
}
@end
加载图片要及时release
你还在使用myImage = [UIImage imageNamed:@"icon.png"]; 吗?
如题,是不是大家为了方便都这样加载图片啊
myImage = [UIImageimageNamed:@"icon.png"];
那么小心了
这种方法在一些图片很少,或者图片很小的程序里是ok的。
但是,在大量加载图片的程序里,请千万不要这样做。
为什么呢 ???????
这种方法在applicationbundle的顶层文件夹寻找由供应的名字的图象。 如果找到图片,装载到iPhone系统缓存图象。那意味图片是(理论上)放在内存里作为cache的。
试想你图片多了,是什么后果?
图片cache极有可能不会响应 memory warnings and releaseits objects
所以,用图片的时候一定要小心的alloc和release。
推荐使用 NSString*path = [[NSBundle mainBundle] pathForResource:@"icon"ofType:@"png"];
myImage = [UIImageimageWithContentsOfFile:path];
// Todo use of myImage
[myImage release];
From: http://www.cocoachina.com/bbs/simple/?t27420.html
uiwebview打开doc,pdf文件
UIWebView *webView = [[UIWebViewalloc]initWithFrame:CGRectMake(0, 55, 320, 300)];
webView.delegate = self;
webView.multipleTouchEnabled = YES;
webView.scalesPageToFit = YES;
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *docPath = [documentsDirectorystringByAppendingString:@"/doc2003_1.doc"]; NSLog(@"#######%@",docPath);
NSURL *url = [NSURL fileURLWithPath:docPath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
[self.view addSubview:webView];
[webViewrelease];
From:http://blog.csdn.net/dadalan/archive/2010/10/22/5959301.aspx
iPhone游戏中既播放背景音乐又播放特效声音的办法
有时候在 iPhone 游戏中,既要播放背景音乐,同时又要播放比如枪的开火音效。此时您可以试试以下方法
NSString *musicFilePath = [[NSBundlemainBundle] pathForResource:fileName ofType:@"wav"]; //创建音乐文件路径
NSURL *musicURL = [[NSURL alloc]initFileURLWithPath:musicFilePath];
AVAudioPlayer* musicPlayer =[[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
[musicURL release];
[musicPlayer prepareToPlay];
//[musicPlayer setVolume:1]; //设置音量大小
//musicPlayer .numberOfLoops = -1;//设置音乐播放次数 -1为一直循环
要导入框架 AVFoundation.framework,头文件中 #import <AVFoundation/AVFoundation.h>;做成类的话则更方便。
From: http://blog.csdn.net/dadalan/archive/2010/10/19/5950493.aspx
NSNotificationCenter用于增加回调函数
[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(_willBecomeActive)name:UIApplicationDidBecomeActiveNotification object:nil];
UINavigationBar 背景Hack
LOGO_320×44.png 图片显示在背景上,
@implementation UINavigationBar(UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
//加入旋转坐标系代码
// Drawing code
UIImage*navBarImage = [UIImage imageNamed:@"LOGO_320×44.png"];
CGContextRefcontext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context,0.0, self.frame.size.height);
CGContextScaleCTM(context,1.0, -1.0);
CGPointcenter=self.center;
CGImageRefcgImage= CGImageCreateWithImageInRect(navBarImage.CGImage, CGRectMake(0, 0, 1,44));
CGContextDrawImage(context,CGRectMake(center.x-160-80, 0, 80, self.frame.size.height), cgImage);
CGContextDrawImage(context,CGRectMake(center.x-160, 0, 320, self.frame.size.height), navBarImage.CGImage);
CGContextDrawImage(context,CGRectMake(center.x+160, 0, 80, self.frame.size.height), cgImage);
}
@end
old code
CGContextDrawImage(context, CGRectMake(0,0, self.frame.size.width, self.frame.size.height), navBarImage.CGImage);
hack 过logo 不再拉伸
From: http://blog.163.com/fengyi1103@126/blog/static/13835627420106279102671/
清除电话号码中的其他符号(源码)
最近从通讯录读取电话号码,读出得号码如:134-1814-****。
而我需要的为11位纯数字,一直找方法解决此问题,今天终于找到了。。
分享一下……
代码如下:
NSString *originalString = @"(123)123123 abc";
NSMutableString *strippedString =[NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScannerscannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:@"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
}
//--------- Add the following to get out of endless loop
else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
//--------- End of addition
}
NSLog(@"%@", strippedString); //"123123123"
From:http://stackoverflow.com/questi*****/1129521/remove-all-but-numbers-from-nsstring
正则判断:字符串只包含字母和数字
NSString *mystring =@"Letter1234";
NSString *regex =@"[a-z][A-Z][0-9]";
NSPredicate *predicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", regex];
if ([predicate evaluateWithObject:mystring]== YES) {
//implement
}
一行代码设置UITableViewCell 与导航条间距
UITableView 的 cell 默认出现在uitableview 的第一行,如果你想自定义UITableViewCell 与导航条间距的话,可以使用下面这行代码
tableview.tableHeaderView= [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)]autorelease];
From: http://blog.163.com/fengyi1103@126/blog/static/1383562742010101611107492/
修改UITableview 滚动条颜色的方法
UITableview 的滚动条默认颜色是黑色的,如果 UItableview 背景也是深颜色,则滚动条会变的很不明显。您可以用下面这行代码来改变滚动条的颜色
self.tableView.indicatorStyle=UIScrollViewIndicatorStyleWhite;
当然,最后的“White”也可以换成其它颜色。
下文件之前获取到文件大小的代码
下面这段代码,能实现在下载文件之前获得文件大小,应用在软件里,能在很大程度上改善用户体验
[m_pASIHTTPRequestsetDidReceiveResp*****eHeadersSelector:@selector(didReceiveResp*****eHeaders:)];
-(void)didReceiveResp*****eHeaders:(ASIHTTPRequest *)request
{
NSLog(@"didReceiveResp*****eHeaders%@",[m_request.resp*****eHeaders valueForKey:@"Content-Length"]);
}
网络编程总结iphone
一:确认网络环境3G/WIFI
1. 添加源文件和framework
开发Web等网络应用程序的时候,需要确认网络环境,连接情况等信息。如果没有处理它们,是不会通过Apple的审(我们的)查的。
Apple 的例程 Reachability 中介绍了取得/检测网络状态的方法。要在应用程序程序中使用Reachability,首先要完成如下两部:
1.1. 添加源文件:
在你的程序中使用 Reachability 只须将该例程中的 Reachability.h 和 Reachability.m 拷贝到你的工程中。如下图:
1.2.添加framework:
将SystemConfiguration.framework 添加进工程。如下图:
2. 网络状态
Reachability.h中定义了三种网络状态:
typedef enum {
NotReachable = 0, //无连接
ReachableViaWiFi, //使用3G/GPRS网络
ReachableViaWWAN //使用WiFi网络
} NetworkStatus;
因此可以这样检查网络状态:
Reachability *r = [ReachabilityreachabilityWithHostName:@“www.apple.com”];
switch ([r currentReachabilityStatus]) {
case NotReachable:
// 没有网络连接
break;
case ReachableViaWWAN:
// 使用3G网络
break;
case ReachableViaWiFi:
// 使用WiFi网络
break;
}
3.检查当前网络环境
程序启动时,如果想检测可用的网络环境,可以像这样
// 是否wifi
+ (BOOL) IsEnableWIFI {
return ([[ReachabilityreachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}
// 是否3G
+ (BOOL) IsEnable3G {
return ([[ReachabilityreachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}
例子:
- (void)viewWillAppear:(BOOL)animated{
if (([ReachabilityreachabilityForInternetConnection].currentReachabilityStatus == NotReachable)&&
([Reachability reachabilityForLocalWiFi].currentReachabilityStatus ==NotReachable)) {
self.navigationItem.hidesBackButton= YES;
[self.navigationItemsetLeftBarButtonItem:nil animated:NO];
}
}
4. 链接状态的实时通知
网络连接状态的实时检查,通知在网络应用中也是十分必要的。接续状态发生变化时,需要及时地通知用户:
Reachability 1.5版本
// My.AppDelegate.h
#import "Reachability.h"
@interface MyAppDelegate : NSObject<UIApplicationDelegate> {
NetworkStatus remoteHostStatus;
}
@property NetworkStatus remoteHostStatus;
@end
// My.AppDelegate.m
#import "MyAppDelegate.h"
@implementation MyAppDelegate
@synthesize remoteHostStatus;
// 更新网络状态
- (void)updateStatus {
self.remoteHostStatus = [[ReachabilitysharedReachability] remoteHostStatus];
}
// 通知网络状态
- (void)reachabilityChanged:(NSNotification*)note {
[self updateStatus];
if (self.remoteHostStatus ==NotReachable) {
UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:NSLocalizedString(@"AppName", nil)
message:NSLocalizedString (@"NotReachable", nil)
delegate:nilcancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
// 程序启动器,启动网络监视
-(void)applicationDidFinishLaunching:(UIApplication *)application {
// 设置网络检测的站点
[[Reachability sharedReachability]setHostName:@"www.apple.com"];
[[Reachability sharedReachability]setNetworkStatusNotificati*****Enabled:YES];
// 设置网络状态变化时的通知函数
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reachabilityChanged:)
name:@"kNetworkReachabilityChangedNotification" object:nil];
[self updateStatus];
}
- (void)dealloc {
// 删除通知对象
[[NSNotificationCenter defaultCenter]removeObserver:self];
[window release];
[super dealloc];
}
Reachability 2.0版本
// MyAppDelegate.h
@class Reachability;
@interface MyAppDelegate : NSObject<UIApplicationDelegate> {
Reachability *hostReach;
}
@end
// MyAppDelegate.m
- (void)reachabilityChanged:(NSNotification*)note {
Reachability* curReach = [note object];
NSParameterAssert([curReachisKindOfClass: [Reachability class]]);
NetworkStatus status = [curReachcurrentReachabilityStatus];
if (status == NotReachable) {
UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:@"AppName""
message:@"NotReachable"
delegate:nil
cancelButtonTitle:@"YES" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
-(void)applicationDidFinishLaunching:(UIApplication *)application {
// ...
// 监测网络情况
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object: nil];
hostReach = [[ReachabilityreachabilityWithHostName:@"www.google.com"] retain];
hostReach startNotifer];
// ...
}
二:使用NSConnection下载数据
1.创建NSConnection对象,设置委托对象
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURL URLWithString:[self urlString]]];
[NSURLConnectionconnectionWithRequest:request delegate:self];
2. NSURLConnection delegate委托方法
- (void)connection:(NSURLConnection*)connection didReceiveResp*****e:(NSURLResp*****e *)resp*****e;
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError *)error;
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data;
- (void)connectionDidFinishLoading:(NSURLConnection*)connection;
3. 实现委托方法
- (void)connection:(NSURLConnection*)connection didReceiveResp*****e:(NSURLResp*****e *)resp*****e {
// store data
[self.receivedData setLength:0]; //通常在这里先清空接受数据的缓存
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data {
/* appends the new data to thereceived data */
[self.receivedDataappendData:data]; //可能多次收到数据,把新的数据添加在现有数据最后
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError *)error {
// 错误处理
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
// disconnect
[UIApplicati*****haredApplication].networkActivityIndicatorVisible = NO;
NSString *returnString = [[NSStringalloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
NSLog(returnString);
[self urlLoaded:[self urlString]data:self.receivedData];
firstTimeDownloaded = YES;
}
三:使用NSXMLParser解析xml文件
1. 设置委托对象,开始解析
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:data]; //或者也可以使用initWithContentsOfURL直接下载文件,但是有一个原因不这么做:
// It's also possible to have NSXMLParserdownload the data, by passing it a URL, but this is not desirable
// because it gives less control over thenetwork, particularly in responding to connection errors.
[parser setDelegate:self];
[parser parse];
2. 常用的委托方法
- (void)parser:(NSXMLParser *)parserdidStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict;
- (void)parser:(NSXMLParser *)parserdidEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName;
- (void)parser:(NSXMLParser *)parserfoundCharacters:(NSString *)string;
- (void)parser:(NSXMLParser *)parserparseErrorOccurred:(NSError *)parseError;
static NSString *feedURLString =@"http://www.yifeiyang.net/test/test.xml";
3. 应用举例
- (void)parseXMLFileAtURL:(NSURL *)URLparseError:(NSError **)error
{
NSXMLParser *parser = [[NSXMLParseralloc] initWithContentsOfURL:URL];
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parsersetShouldReportNamespacePrefixes:NO];
[parsersetShouldResolveExternalEntities:NO];
[parser parse];
NSError *parseError = [parserparserError];
if (parseError && error) {
*error = parseError;
}
[parser release];
}
- (void)parser:(NSXMLParser *)parserdidStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString*)qName attributes:(NSDictionary *)attributeDict{
// 元素开始句柄
if (qName) {
elementName = qName;
}
if ([elementName isEqualToString:@"user"]){
// 输出属性值
NSLog(@"Name is %@ , Age is%@", [attributeDict objectForKey:@"name"], [attributeDictobjectForKey:@"age"]);
}
}
- (void)parser:(NSXMLParser *)parserdidEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
// 元素终了句柄
if (qName) {
elementName = qName;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString*)string
{
// 取得元素的text
}
NSError *parseError = nil;
[self parseXMLFileAtURL:[NSURLURLWithString:feedURLString] parseError:&parseError];
Iphone 实现画折线图
iphone里面要画图一般都是通过CoreGraphics.framwork和QuartzCore.framwork实现,apple的官方sdk demon中包含了QuartzCore的基本用法,
具体demo请参考http://developer.apple.com/library/ios/#samplecode/QuartzDemo/
折线图
要实现折线图也就把全部的点连起来,movePointLineto,具体的调用里面的api就可以实现了,但是画坐标就比较麻烦了,里面需要去转很多,好在国外有人开源了一个画折线图的开发包,首先看看效果吧,具体怎么用可以参考作者git版本库中的wiki。
http://github.com/devinross/tapkulibrary/wiki/How-To-Use-This-Library
这个包还提供了其他的很好看的UI,都可以调来用,但是我们只需要一个画图要把整个包都导进去,工程太大了,既然是开源的那就想办法提取出来吧,原先之前也有人干过这样的事。http://duivesteyn.net/2010/03/07/iphone-sdk-implementing-the-tapku-graph-in-your-application/
我对源代码进行简单的修改,使其显示坐标之类的,更加符合工程的需要,但是还没有实现画多组数据,只能画一组数据,不用viewContol,而使用addsubview,直接添加到当前的窗口,最终效果如下。
使用方法:
1.工程添加tk库里面的如下文件
2. 添加QuartzCore framework
#import <QuartzCore/QuartzCore.h>
添加TapkuLibrary.bundle资源文件
3.代码中完成实例,数据初始化就可以用了
[/url] [url=http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/image133.png]下载修改后的版本。下次有时间在整理一个工程版本出来。
让iPhone屏幕常亮不变暗的方法
如果您希望运行自己开发的App时,iPhone的屏幕不再自动变暗,可以使用以下方法让屏幕常亮: iPhone OS用一个布尔值用来控制是否取消应用程序空闲时间:@property(nonatomic,getter=isIdleTime
如果您希望运行自己开发的App时,iPhone的屏幕不再自动变暗,可以使用以下方法让屏幕常亮:
iPhone OS用一个布尔值用来控制是否取消应用程序空闲时间:@property(nonatomic, getter=isIdleTimerDisabled) BOOLidleTimerDisabled。这个值的默认属性是"NO"。当大多数应用程序没有接收到用户输入信息的时候,系统会把设备设置成“休眠”状态,iPhone屏幕也会变暗。这样做是为了保存更多电量。事实上,应用程序在运行加速度游戏的时候是不需要用户输入的,当然这里只是一个假设,把这个变量设置为"YES",来取消系统休眠的“空闲时间”。
重点是:你必须当真正需要的时候才打开这个属性当你不用的时候马上还愿成"NO"。大多数应用程序在休眠时间到的时候让系统关闭屏幕。这个包括了有音频的应用程序。在Audio Session Services中使用适当的回放和记录功能不会被间断当屏幕关闭时。只有地图应用程序,游戏或者一些不间断的用户交互程序可以取消这个属性。
苹果开发网络编程知识总结
以下苹果开发网络编程知识由 CocoaChina 会员 cocoa_yang 总结,希望能为苹果开发新手梳理知识脉络,节省入门时间。一:确认网络环境3G/WIFI 1. 添加源文件和framework 开发Web等网络应用程序
以下苹果开发网络编程知识由 CocoaChina 会员 “cocoa_yang” 总结,希望能为苹果开发新手梳理知识脉络,节省入门时间。
一:确认网络环境3G/WIFI
1. 添加源文件和framework
开发Web等网络应用程序的时候,需要确认网络环境,连接情况等信息。如果没有处理它们,是不会通过Apple的审查的。
Apple 的例程 Reachability 中介绍了取得/检测网络状态的方法。要在应用程序程序中使用Reachability,首先要完成如下两部:
1.1. 添加源文件:
在你的程序中使用 Reachability 只须将该例程中的 Reachability.h 和 Reachability.m 拷贝到你的工程中。如下图:
1.2.添加framework:
将SystemConfiguration.framework 添加进工程。如下图:
2. 网络状态
Reachability.h中定义了三种网络状态:
typedef enum {
NotReachable = 0, //无连接
ReachableViaWiFi, //使用3G/GPRS网络
ReachableViaWWAN //使用WiFi网络
} NetworkStatus;
因此可以这样检查网络状态:
Reachability *r = [ReachabilityreachabilityWithHostName:@“www.apple.com”];
switch ([r currentReachabilityStatus]) {
case NotReachable:
// 没有网络连接
break;
case ReachableViaWWAN:
// 使用3G网络
break;
case ReachableViaWiFi:
// 使用WiFi网络
break;
}
3.检查当前网络环境
程序启动时,如果想检测可用的网络环境,可以像这样
// 是否wifi
+ (BOOL) IsEnableWIFI {
return ([[ReachabilityreachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}
// 是否3G
+ (BOOL) IsEnable3G {
return ([[ReachabilityreachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}
例子:
- (void)viewWillAppear:(BOOL)animated{
if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus== NotReachable) &&
([ReachabilityreachabilityForLocalWiFi].currentReachabilityStatus == NotReachable)) {
self.navigationItem.hidesBackButton= YES;
[self.navigationItemsetLeftBarButtonItem:nil animated:NO];
}
}
4. 链接状态的实时通知
网络连接状态的实时检查,通知在网络应用中也是十分必要的。接续状态发生变化时,需要及时地通知用户:
Reachability 1.5版本
// My.AppDelegate.h
#import "Reachability.h"
@interface MyAppDelegate : NSObject<UIApplicationDelegate> {
NetworkStatus remoteHostStatus;
}
@property NetworkStatus remoteHostStatus;
@end
// My.AppDelegate.m
#import "MyAppDelegate.h"
@implementation MyAppDelegate
@synthesize remoteHostStatus;
// 更新网络状态
- (void)updateStatus {
self.remoteHostStatus = [[ReachabilitysharedReachability] remoteHostStatus];
}
// 通知网络状态
- (void)reachabilityChanged:(NSNotification*)note {
[self updateStatus];
if (self.remoteHostStatus ==NotReachable) {
UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:NSLocalizedString(@"AppName", nil)
message:NSLocalizedString (@"NotReachable", nil)
delegate:nilcancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
// 程序启动器,启动网络监视
-(void)applicationDidFinishLaunching:(UIApplication *)application {
posted on 2012-09-18 16:43 I am fine ! 阅读(496) 评论(0) 编辑 收藏 举报