IOS必备小技巧

退回输入键盘

- (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);

);

设置透明度

[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:[UIScreen mainScreen] 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

http://pic002.cnblogs.com/images/2011/162291/2011121611431816.png

http://pic002.cnblogs.com/images/2011/162291/2011121611432897.png

-(IBAction)sliderValueChanged:(id)sender{

UISlider *slider = (UISlider *) sender;

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

label.text = newText;

label.text = newText

}

活动表单

- (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];

}

警告视图

- (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  

#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

#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 {

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];

[[NSUserDefaults standardUserDefaults] objectForKey:aKey];

NSNotification

自定义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;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,657评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,662评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,143评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,732评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,837评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,036评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,126评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,868评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,315评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,641评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,773评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,470评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,126评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,859评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,095评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,584评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,676评论 2 351

推荐阅读更多精彩内容