首页 > 代码库 > iOS 学习
iOS 学习
1、UISearchBar自定义背景、取消按钮中文设置
C代码
- UISearchBar *seachBar=[[UISearchBar alloc] init];
- //修改搜索框背景
- seachBar.backgroundColor=[UIColor clearColor];
- //去掉搜索框背景
- [[searchbar.subviews objectAtIndex:0]removeFromSuperview];
- for (UIView *subview in seachBar.subviews)
- {
- if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
- {
- [subview removeFromSuperview];
- break;
- }
- }
- //自定义背景
- UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"40-di.png"]];
- [searchBar insertSubview:imageView atIndex:1];
- //输入搜索文字时隐藏搜索按钮,清空时显示
- - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
- searchBar.showsScopeBar = YES;
- [searchBar sizeToFit];
- [searchBar setShowsCancelButton:YES animated:YES];
- return YES;
- }
- - (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
- searchBar.showsScopeBar = NO;
- [searchBar sizeToFit];
- [searchBar setShowsCancelButton:NO animated:YES];
- return YES;
- }
- //修改UISearchBar取消按钮中文字体
- for (id aa in [searchBar subviews]) {
- if ([aa isKindOfClass:[UIButton class]]) {
- UIButton *btn = (UIButton *)aa;
- [btn setTitle:@"取消" forState:UIControlStateNormal];
- }
- }
2、UISearchBar
C代码
- #pragma mark 搜索控件
- //搜索
- - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
- UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
- FirstViewController *fVC = [mainStory instantiateViewControllerWithIdentifier:@"goFirstView"];
- fVC.showStr = self.searchBar.text;
- [self presentModalViewController:fVC animated:YES];
- }
- //搜索输入内容时触发
- - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
- }
- //焦点进入搜索
- - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
- self.soundBtn.hidden = YES;
- [self searchBar:searchBar activate:YES];
- }
- //取消搜索按钮
- - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
- self.searchBar.text = @"";
- self.soundBtn.hidden = NO;
- [self searchBar:searchBar activate:NO];
- }
- - (void)searchBar:(UISearchBar *)searchBar activate:(BOOL) active{
- if (!active) {
- [self.searchBar resignFirstResponder];
- }
- [self.searchBar setShowsCancelButton:active animated:YES];
- //修改UISearchBar取消按钮字体
- for (id aa in [searchBar subviews]) {
- if ([aa isKindOfClass:[UIButton class]]) {
- UIButton *btn = (UIButton *)aa;
- [btn setTitle:@"取消" forState:UIControlStateNormal];
- }
- }
- }
3、NSNotificationCenter通告中心
NSNotificationCenter通告与一个按钮中用addTarget绑定方法有些相似,按钮中的绑定触发事件时才调用关联消息。而NSNotificationCenter的范围则大得多,比如说摇动中,当触发摇动事件时,就提交并触发消息。
示例如下:
C代码
- //1、需触发的消息方法
- - (void) testNotification{
- NSLog(@"测试通告中心。。。。。。。");
- }
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- //2、对象注册,关联消息
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(testNotification) name:@"Dwen_Notification" object:nil];
- }
- #pragma 通告中心
- - (IBAction)notificationTest:(id)sender {
- //3、提交消息
- [[NSNotificationCenter defaultCenter] postNotificationName:@"Dwen_Notification" object:@"Request Object"];
- }
4、视图显示和消失将会调用的方法,可处理一些前一界面的还原初始状态。
- (void) viewWillDisappear: 视图消失时调用
- (void) viewWillAppear: 进入视图时调用
例如:点击搜索后,会的取消按钮,跳到下一界面再返回时,需把取消按钮隐藏掉可通过它们处理。
5、获取程序的AppDelegate
AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
6、ios4跳转界面
C代码
- QuotaManageViewController *qmvc = [[QuotaManageViewController alloc] init];
- [self.navigationController pushViewController:qmvc animated:YES];
- [qmvc release];
7、UILable换行
C代码
- lab_1.lineBreakMode = UILineBreakModeWordWrap;
- lab_1.numberOfLines = 0;
8、ipad中设置tableview背景无效,有两种解决方法:
方法一:
C代码
- UIView *view = [[UIView alloc] init];
- view.backgroundColor = [UIColor clearColor];
- tableView2.backgroundView = view;
方法二:
C代码
- if ([self.tableView2 respondsToSelector:@selector(backgroundView)]) {
- self.tableView2.backgroundView = nil;
- }
9、自定义UIView时,会继承它,下面是如何加载UIView对应xib。
C代码
- UIView *head_View = [[[NSBundle mainBundle] loadNibNamed:@"HeadView" owner:self options:nil] lastObject];
- head_View.frame = CGRectMake(0, -120, self.view.frame.size.width, 150);
- head_View.backgroundColor = [UIColor brownColor];
- [self.view addSubview:head_View];
10、对UIView进行旋转。2012-11-07
今天在做ipad时,弹出的pop视图,总是横屏放着,不能竖屏。纠结了些时间,后来通过修改视图的坐标解决了该问题。
C代码
- CGAffineTransform at = CGAffineTransformMakeRotation(M_PI/2);//顺时钟旋转90
- at = CGAffineTransformTranslate(at, 200, 0);
- [popVC.view setTransform:at];
11、关于在UIView上进行滑动手势和点击事件手势。
C代码
- ///////////注flowView为UIView//////////
- //添加滑动手势事件
- UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:flowView action:@selector(handleGesture:)];
- [flowView addGestureRecognizer:gestureRecognizer];
- //添加点击手势事件
- flowView.userInteractionEnabled = YES;
- UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:flowView action:@selector(goBigImageView)];
- [flowView addGestureRecognizer:tap];
C代码
- //滑动手势(里面有手势的不同状态,根据需要进行灵活运用)
- - (void)handleGesture:(UIPanGestureRecognizer *)recognizer {
- //UITapGestureRecognizer
- if (recognizer.state == UIGestureRecognizerStateChanged){
- NSLog(@"UIGestureRecognizerStateChanged");
- }else if(recognizer.state == UIGestureRecognizerStateEnded){
- NSLog(@"UIGestureRecognizerStateEnded");
- }else if(recognizer.state == UIGestureRecognizerStateBegan){
- NSLog(@"UIGestureRecognizerStateBegan");
- }else if(recognizer.state == UIGestureRecognizerStateCancelled){
- NSLog(@"UIGestureRecognizerStateCancelled");
- }else if(recognizer.state == UIGestureRecognizerStateFailed){
- NSLog(@"UIGestureRecognizerStateFailed");
- }else if(recognizer.state == UIGestureRecognizerStatePossible){
- NSLog(@"UIGestureRecognizerStatePossible");
- }else if(recognizer.state == UIGestureRecognizerStateRecognized){
- NSLog(@"UIGestureRecognizerStateRecognized");
- }
- }
12、启动时异常
Couldn‘t register com.yourcompany.ReciteWords with the bootstrap server. Error: unknown error code.
This generally means that another instance of this process was already running or is hung in the debugger
解决方法,重启设备或模拟器
13、读写plist文件
C代码
- - (void)readWritePlist{
- //获取路径
- NSString *homePath = [[NSBundle mainBundle] executablePath];
- NSArray *strings = [homePath componentsSeparatedByString: @"/"];
- NSString *executableName = [strings objectAtIndex:[strings count]-1];
- NSString *baseDirectory = [homePath substringToIndex:
- [homePath length]-[executableName length]-1];
- //data.plist文件
- NSString *filePath = [NSString stringWithFormat:@"%@/data.plist",baseDirectory];
- NSLog(@"filePath: %@",filePath);
- NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
- NSLog(@"dataDict: %@",dataDict);
- //change the value or add the value
- [dataDict setObject:@"YES" forKey:@"Trial"];
- [dataDict setValue:@"dwen" forKey:@"nickName"];
- //write back to data.plist file
- [dataDict writeToFile:filePath atomically:NO];
- }
14、ios生成随机数(三种方式):
int i = rand() % 5;
int i = random() % 5;
int x = arc4random() % 100;//[0,100] 包括0 ,不包括100
int y = (arc4random() % 501) + 500;//[500,1000 ],包括500 ,不包括1000
15、UIImage图片处理:缩放、设定大小、存储(转载)
C代码
- //1.等比率缩放
- - (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize{
- UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize);
- [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
- UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- return scaledImage;
- }
- //2.自定长宽
- - (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize{
- UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
- [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
- UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- return reSizeImage;
- }
- //3.处理某个特定View
- 只要是继承UIView的object 都可以处理
- 必须先import QuzrtzCore.framework
- -(UIImage*)captureView:(UIView *)theView{
- CGRect rect = theView.frame;
- UIGraphicsBeginImageContext(rect.size);
- CGContextRef context = UIGraphicsGetCurrentContext();
- [theView.layer renderInContext:context];
- UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- return img;
- }
- //4.储存图片
- 储存图片这里分成储存到app的文件里, 储存到手机的图片库里
- // 储存到app的文件里
- NSString *path = [[NSHomeDirectory()stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"image.png"];
- [UIImagePNGRepresentation(image) writeToFile:pathatomically:YES];
16、object-c正则验证,方式之一,如下:
NSPredicate用于指定过滤器的条件。通过该对象准确地描述所需条件,对每个对象通过谓词进行筛选,判断它们是否与条件相匹配。
C代码
- NSString *numberRegex = @"[1-4]";
- NSPredicate *number = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",numberRegex];
- bool result = [number evaluateWithObject:@"1"];
17、定义程序块
C代码
- //定义程序块
- void(^loggerBlock)(void);
- //实现程序块
- loggerBlock = ^{NSLog(@"i am test block.");};
- //执行程序块
- loggerBlock();
18、反射
C代码
- //反射(对CodingVo类进行反射)
- Class cls = NSClassFromString(@"CodingVo");
- id obj = [[cls alloc] init];
- SEL selector = NSSelectorFromString(@"test1");
- //调用CodingVo类中test1方法
- [obj performSelector:selector withObject:nil];
19、调用短信、电话、邮件、Safari浏览器API
C代码
- //调用短信
- - (IBAction)callMsg:(id)sender {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://135587"]];
- }
- //调用电话
- - (IBAction)callTel:(id)sender {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://135587"]];
- }
- //调用Safari浏览器
- - (IBAction)callSafari:(id)sender {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.baidu.com/"]];
- }
- // 调用email
- - (IBAction)callEmail:(id)sender {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://test@126.com"]];
- }
20、操作声音文件,添加AudioToolbox.framework库。
#import <AudioToolbox/AudioToolbox.h>
@property (assign,nonatomic) SystemSoundID soundID;
//测试播放声音
- (void) testSound{
NSString *path = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"caf"];
NSURL *url = [NSURL fileURLWithPath:path];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);
AudioServicesPlaySystemSound(soundID);
NSLog(@"testSound...mp3音频文件格式不支持");
}
21、ios触摸事件监听和操作(UITouch)
C代码
- //手指触摸屏幕时报告
- - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
- NSLog(@"touchesBegan");
- }
- //手指在屏幕上移动时报告
- - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
- NSLog(@"touchesMoved");
- }
- //手指离开屏幕时报告
- - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
- NSLog(@"touchesEnded");
- }
- //因接听电话或其他因素导致取消触摸时报告
- - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
- NSLog(@"touchesCancelled");
- }
22、\u00B0表示角度符号
NSString *latitudeStr = [NSString stringWithFormat:@"%g\u00B0",newLocation.coordinate.latitude];
23、实现ios动画效果有两种方式,一种是UIView层面上的,另一种是CATransation更底层次控制
24、设备信息
NSLog(@"系统名称:%@ ,系统版本: %@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion]);
25、MPMoviePlayerViewController控件中,需把Done改为中文,对工程中plist文件进行设置。对其他英文控件中的英文文本也有同样有效。设置见下图:
26、文本层CATextLayer
C代码
- CATextLayer *txtLayer = [CATextLayer layer];
- txtLayer.string = @"地球";
- txtLayer.foregroundColor = [[UIColor redColor] CGColor];
- txtLayer.bounds = CGRectMake(0, 0, 200, 50);
- txtLayer.position = CGPointMake(0, 0);
- [imageLayer addSublayer:txtLayer];
27、assign、retain、copy、readonly区别
assign:指定setter方法用简单的赋值,这是默认操作。你可以对标量类型(如int)使用这个属性。你可以想象一个float,它不是一个对象,所以它不能retain、copy。
retain:指定retain应该在后面的对象上调用,前一个值发送一条release消息。你可以想象一个NSString实例,它是一个对象,而且你可能想要retain它。
copy:指定应该使用对象的副本(深度复制),前一个值发送一条release消息。基本上像retain,但是没有增加引用计数,是分配一块新的内存来放置它。
readonly:将只生成getter方法而不生成setter方法(getter方法没有get前缀)。
readwrite:默认属性,将生成不带额外参数的getter和setter方法(setter方法只有一个参数)。
atomic:对于对象的默认属性,就是setter/getter生成的方法是一个原子操作。如果有多个线程同时调用setter的话,不会出现某一个线程执行setter全部语句之前,另一个线程开始执行setter的情况,相关于方法头尾加了锁一样。
nonatomic:不保证setter/getter的原子性,多线程情况下数据可能会有问题
28、声明关键字前加extern,为外部变量。外部变量可被其他任何方法或函数访问和更改其值的变量。