exclusiveforce touch是什么么属性

iOS 开发总结 - 推酷
iOS 开发总结
&&& NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& (CFStringRef)string,NULL,CFSTR(&!*'();:@&=+$,/?%#[]&),kCFStringEncodingUTF8);
&&& [result autorelease];
- (NSString *)generateNonce{
&&& CFUUIDRef theUUID = CFUUIDCreate(NULL);
&&& CFStringRef string = CFUUIDCreateString(NULL, theUUID);
&&& NSMakeCollectable(theUUID);
&&& return [(NSString *)string stringByReplacingOccurrencesOfString:@&-& withString:@&&];
&&& //return (NSString *)
- (NSString *)generateTimestamp{
&&& return [[NSString stringWithFormat:@&%d&, time(NULL)] retain];
iPhone 键盘改变颜色
只有 这 2 种数字 键盘才有效果: UIKeyboardTypeNumberPad , UIKeyboardTypePhonePad
keyboardAppearance = UIKeyboardAppearanceAlert
代 码如下:
&&&NSArray *ws = [[UIApplication sharedApplication] windows];
&&&&for(UIView *w in ws){
&&&&&&&&NSArray *vs = [w subviews];
&&&&&&&&for(UIView *v in vs){
&&&&&&&&&&&&if([[NSString stringWithUTF8String:object_getClassName(v)] isEqualToString:@&UIKeyboard&]){
&&&&&&&&&&&&&&&&v.backgroundColor = [UIColor redColor];
&&&&&&&&&&&&}
从一个界面
到下一界面左上角返回按 钮文字设置
在父 viewController 中如下 设置:
&&&&UIBarButtonItem *backbutton = [[UIBarButtonItem alloc]init];
&&&&backbutton.title = @& 返回列表 &;
&&&&self.navigationItem.backBarButtonItem =
&&&&[backbutton release];
navigationbar
back 键触发其他事件
UIButton *back =[[UIButton alloc] initWithFrame:CGRectMake(200, 25, 63, 30)];
[back addTarget:self action:@selector(reloadRowData:) forControlEvents:UIControlEventTouchUpInside];
[back setImage:[UIImage imageNamed:@& 返回按 钮 .png&] forState:UIControlStateNormal];
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];
self.navigationItem.leftBarButtonItem = loginButtonItem
[back release];
[backButtonItem release];
防止屏幕暗掉 锁屏
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
图片从左到右翻页效果显示
&&& UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 470)];
&&& [imageView setImage:[UIImage imageNamed:@&Bg.jpg&]];
&&& self.myImageView =imageV
&&& [self.view addSubview:imageView];
&&& [imageView release];
&&& CGContextRef context = UIGraphicsGetCurrentContext();
&&& [UIView beginAnimations:nil context:context];
&&& [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
&&& [UIView setAnimationDuration:0.5];
&&& [myImageView setFrame:CGRectMake(0, 0, 310, 470)];&&&
&&& [UIView commitAnimations];
让覆盖在下面层的视图接受触摸事件
searchImage.exclusiveTouch = YES;// 第一 层
searchImage.userInteractionEnabled = NO;
myMapView.exclusiveTouch = NO;// 第二 层
myMapView.userInteractionEnabled = YES;
NSValue *touchPointValue = [[NSValue valueWithCGPoint:CGPointMake(100,100)] retain];
[UIView beginAnimations:nil context:touchPointValue];
transform = CGAffineTransformMakeScale(0.1,0.21);
firstPieceView.transform =
[UIView commitAnimations];&&&
码循环添加按钮,其他空间也可以用类似方法添加
- (void)viewDidLoad {
&&&&[super viewDidLoad];
&&&&for(int i = 0; i & 5; i++){
&&&&&&&&CGR
&&&&&&&&Btn[i] = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
&&&&&&&&[Btn[i] setImage:[UIImage imageNamed:@&Button.png&] forState:UIControlStateNormal];// 设置按钮图片
&&&&&&&&frame.size.width = 55;// 设置按钮坐标及大小
&&&&&&&&frame.size.height = 84;
&&&&&&&&frame.origin.x = (i%5)*57+5;
&&&&&&&&frame.origin.y = 10;
&&&&&&&&[Btn[i] setFrame:frame];
&&&&&&&&[Btn[i] setBackgroundColor:[UIColor clearColor]];
&&&&&&&&[Btn[i] addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
&&&&&&&&[self.view addSubview:Btn[i]];
&&&&&&&&[Btn[i] release];
响 应按钮事件
-(void)btnPressed:(id)sender{
&&&&for(int i = 0; i & 5;i++){
&&&&&&&&if([sender isEqual:Btn[i]]){
&&&&&&&&&&&&NSLog(@&Btn[%d]:&,i);
中的空格,
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet ];
NSString * username = [mUsernameField stringValue];
username = [username stringByTrimmingCharactersInSet :whitespace];
UIImagePickerController
用 UIImagePickerController 选择、显示图片或视频,主要注意 UIImagePickerController 几个属性的 设置
显示样式,显示的格式确定
1 : sourceType
@property(nonatomic) UIImagePickerControllerSourceType sourceType
UIImagePickerControllerSourceTypePhotoLibrary,
UIImagePickerControllerSourceTypeCamera,
UIImagePickerControllerSourceTypeSavedPhotosAlbum
typedef NSUInteger UIImagePickerControllerSourceT
sourceType
确定用 户界面显示的样式:
共三种格式(模 拟器上的效果图)
UIImagePickerControllerSourceTypePhotoLibrary,
UIImagePickerControllerSourceTypeCamera,
UIImagePickerControllerSourceTypeSavedPhotosAlbum
为了区分是否支持视频格式,一般要用到下面这个函数,以便确定
+ (BOOL)isSourceTypeAvailable:(UIImagePickerControllerSourceType)sourceType
2:&& mediaTypes
@property(nonatomic,copy) NSArray *mediaTypes
用来确定再
里 显示那些类型的多媒体文件,图片?视频?
+ (NSArray *)availableMediaTypesForSourceType:(UIImagePickerControllerSourceType)sourceType
二: 选取动作处理
UIImagePickerControllerDelegate
通 过代理来完成用户在选中图片,或者
视频时的处理方式:
共有三个可 选的代理方法
– imagePickerController:didFinishPickingMediaWithInfo:&
– imagePickerControllerDidCancel:&
– imagePickerController:didFinishPickingImage:editingInfo:&& Deprecated in iPhone OS 3.0
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
中包括 选取的照片,视频的主要信息
NSString *const UIImagePickerControllerMediaT&&&&&&&& 选取的类型 public.image& public.movie
NSString *const UIImagePickerControllerOriginalI&&& 修改前的 UIImage object.
NSString *const UIImagePickerControllerEditedI&&&&& 修改后的 UIImage object.
NSString *const UIImagePickerControllerCropR 原始 图片的尺寸 NSValue object containing a CGRect data type
NSString *const UIImagePickerControllerMediaURL;&&&&&&&&& 视频在文件系统中 的 NSURL 地址
保存 视频主要时通过获取其
然后 转换成
实例代码如下:
- (void) pickImage: (id) sender
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
&&&&&&& if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
&&&& ipc.sourceType =& UIImagePickerControllerSourceTypePhotoL
&&&&& ipc.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:ipc.sourceType];&&
& & & & }&
ipc.delegate =
ipc.allowsImageEditing = NO;
[self presentModalViewController:ipc animated:YES];
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:@&public.image&]){
// UIImage *selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImage *image = [info objectForKey:@&UIImagePickerControllerOriginalImage&];
& & NSLog(@&found an image&);
[UIImageJPEGRepresentation(image, 1.0f) writeToFile:[self findUniqueSavePath] atomically:YES];
& & SETIMAGE(image);
CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@&/Documents&]]);
else if ([mediaType isEqualToString:@&public.movie&]){
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(@&found a video&);
& & & & NSData *webData = [NSData dataWithContentsOfURL:videoURL];
//NSData *video = [[NSString alloc] initWithContentsOfURL:videoURL];
[webData writeToFile:[self findUniqueMoviePath] atomically:YES];
CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:@&/Documents&]]);
// NSLog(videoURL);
[picker dismissModalViewControllerAnimated:YES];
UITextInputTraits
& autocapitalizationType&&&&&&&&&&& 设置键盘自动大小写的属性 &&&& UITextAutocapitalizationTypeNone
autocorrectionType& property& 设置是否有自动修改提示 && UITextAutocorrectionTypeNo
enablesReturnKeyAutomatically&& Boolean 值-设置在用户没有输入是 returnKey
keyboardAppearance& 设置键盘显示方式 &
认模式 & 还有一个 UIKeyboardAppearanceAlert
keyboardType&&&&&&&&&&&&&& 设置键盘类型 && UIKeyboardTypePhonePad
returnKeyType&&&&&&&&&&&&& 设置 renturnKey
键上的提示文字 &&&& UIReturnKeyGo&& UIReturnKeyNext
secureTextEntry&&&&&&&&&& BOOL 值 & -- 设置是否是密码保护模式输入
设置登录用的 输入框 UITextField
用 户名输入框:
m_TF_username = [[UITextField alloc] initWithFrame:my_frame];
m_TF_username.borderStyle = UITextBorderStyleN
m_TF_username.clearButtonMode = UITextFieldViewModeWhileE
m_TF_username.delegate =
m_TF_username.returnKeyType = UIReturnKeyN
m_TF_username.autocapitalizationType = UITextAutocapitalizationTypeN
[m_TF_username becomeFirstResponder];
密 码输入框:
m_TF_password = [[UITextField alloc] initWithFrame:my_frame];
m_TF_password.borderStyle = UITextBorderStyleN
m_TF_password.clearButtonMode = UITextFieldViewModeWhileE
m_TF_password.delegate =
m_TF_password.returnKeyType = UIReturnKeyGo;
m_TF_password.secureTextEntry =YES;
textField.keyboardAppearance = UIKeyboardAppearanceA
态栏的网络活动风火轮是否旋转
[UIApplication sharedApplication].networkActivityIndicatorVisible ,默 认值是 NO 。
截取屏幕 图片
// 创建一个基于位图的图形上下文并指定大小为 CGSizeMake(200,400)
UIGraphicsBeginImageContext(CGSizeMake(200,400));
//renderInContext 呈 现接受者及其子范围到指定的上下文
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
返回一个基于当前 图形上下文的图片
&UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();
移除 栈顶的基于当前位图的图形上下文
UIGraphicsEndImageContext();
格式返回指定 图片的数据
imageData = UIImagePNGRepresentation(aImage);
选中的背景
&&& UIView *myview = [[UIView alloc] init];
&&& myview.frame = CGRectMake(0, 0, 320, 47);
&&& myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@&0006.png&]];
&&& cell.selectedBackgroundView =
键盘上添加 button
定 义一个消息中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; //addObserver: 注册一个 观察员 name: 消息名称
- (void)keyboardWillShow:(NSNotification *)note {
&&& // create custom button
&&& UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
&&& doneButton.frame = CGRectMake(0, 163, 106, 53);
&&& [doneButton setImage:[UIImage imageNamed:@&5.png&] forState:UIControlStateNormal];
&&& [doneButton addTarget:self action:@selector(addRadixPoint) forControlEvents:UIControlEventTouchUpInside];
&&& // locate keyboard view
&&& UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];// 返回 应用程序 window
&&& UIView*
&&& for(int i=0; i&[tempWindow.subviews count]; i++) // 遍 历 window 上的所有 subview
&&& &&& keyboard = [tempWindow.subviews objectAtIndex:i];
&&& &&& // add the custom button to it
&&& &&& if([[keyboard description] hasPrefix:@&&UIKeyboard&] == YES)
&&& &&& [keyboard addSubview:doneButton];
则表达式使用:
被用于正 则表达式的字串必须是可变长的,不然会出问题
间放在视图之上
[scrollView insertSubview:searchButton aboveSubview:scrollView];
从本地加 载图片
NSString *boundle = [[NSBundle mainBundle] resourcePath];
[web1 loadHTMLString:[NSString stringWithFormat:@&&img src='http://fei263./blog/0001.png'/&&] baseURL:[NSURL fileURLWithPath:boundle]];
页加载图片并让图片在规定长宽中缩小
[cell.img loadHTMLString:[NSString stringWithFormat:@&&html&&body&&img src='http://fei263./blog/%@' height='90px' width='90px'&&/body&&/html&&,goodsInfo.GoodsImg] baseURL:nil];
将网 页加载到
获取里面的数据,如果只是发送了一个连接请求获取到源码以后可以用正则表达式进行获取数据
NSString *javaScript1 = @&document.getElementsByName('.u').item(0).value&;
NSString *javaScript2 = @&document.getElementsByName('.challenge').item(0).value&;
NSString *strResult1 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript1]];
NSString *strResult2 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript2]];
UTF8 转换成 unicode
utf8Str //
NSString *unicodeStr = [NSString stringWithCString:[utf8Str UTF8String] encoding:NSUnicodeStringEncoding];
调用自己的方法
[self performSelector:@selector(loginToNext) withObject:nil afterDelay:2];// 黄色段 为方法名 , 和延 迟几秒执行 .
CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:@&myImage.png&]];
myImage.opaque = YES; //opaque 是否透明
[self.view addSubview:myImage];
[myImage release];
CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);
UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];
[webView setBackgroundColor:[UIColor whiteColor]];
NSString *urlAddress = @&&;
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self addSubview:webView];
[webView release];
显示网络活动状态指示符
左上部的状 态栏显示的转动的图标指示有背景发生网络的活动。
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
一个接一个地
显示一系列的图象
NSArray *myImages = [NSArray arrayWithObjects: [UIImage imageNamed:@&myImage1.png&], [UIImage imageNamed:@&myImage2.png&], [UIImage imageNamed:@&myImage3.png&], [UIImage imageNamed:@&myImage4.gif&], nil];
UIImageView *myAnimatedView = [UIImageView alloc];
[myAnimatedView initWithFrame:[self bounds]];
myAnimatedView.animationImages = myI //animationImages 属性返回一个存放 动画图片的数组
myAnimatedView.animationDuration = 0.25; // 浏览整个图片一次所用的时间
myAnimatedView.animationRepeatCount = 0; // 0 = loops forever 动画重复次数
[myAnimatedView startAnimating];
[self addSubview:myAnimatedView];
[myAnimatedView release];
在屏幕上移
动。注:这种类型的动画是
获取任何有关物体在动画中的信息
如当前的位置
。如果您需要此信息,您会手
动使用定时器去调整动画的
这个需要导入 QuartzCore.framework
CABasicAnimation *theA
theAnimation=[CABasicAnimation animationWithKeyPath:@&transform.translation.x&];
//Creates and returns an CAPropertyAnimation instance for the specified key path.
//parameter:the key path of the property to be animated
theAnimation.duration=1;
theAnimation.repeatCount=2;
theAnimation.autoreverses=YES;
theAnimation.fromValue=[NSNumber numberWithFloat:0];
theAnimation.toValue=[NSNumber numberWithFloat:-60];
[view.layer addAnimation:theAnimation forKey:@&animateLayer&];
Draggable items//
Here's how to create a simple draggable image.// 这是如何生成一个简单的拖动图象
1. Create a new class that inherits from UIImageView
@interface myDraggableImage : UIImageView { }
2. In the implementation for this new class, add the 2 methods:
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
// Retrieve the touch point 检索接触点
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation =
[[self superview] bringSubviewToFront:self];
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
// Move relative to the original touch point 相 对以前的触摸点进行移动
CGPoint pt = [[touches anyObject] locationInView:self];
CGRect frame = [self frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[self setFrame:frame];
3. Now instantiate the new class as you would any other new image and add it to your view
实例这个新的类
放到你需要新的 图片放到你的视图上
dragger = [[myDraggableImage alloc] initWithFrame:myDragRect];
[dragger setImage:[UIImage imageNamed:@&myImage.png&]];
[dragger setUserInteractionEnabled:YES];
1. Create the new thread:
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
2. Create the method that is called by the new thread:
- (void)myMethod
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
*** code that should be run in the new thread goes here ***
[pool release];
//What if you need to do something to the main thread from inside your new thread (for example, show a loading //symbol)? Use performSelectorOnMainThread.
[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];
Plist files
Application-specific plist files can be stored in the Resources folder of the app bundle. When the app first launches, it should check if there is an existing plist in the user's Documents folder, and if not it should copy the plist from the app bundle.
// Look in Documents for an existing plist file
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: @&%@.plist&, plistName] ];
[myPlistPath retain];
// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:myPlistPath] )
NSString *pathToSettingsInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@&plist&];
//Now read the plist file from Documents
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@&myApp.plist&];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
//Now read and set key/values
myKey = (int)[[plist valueForKey:@&myKey&] intValue];
myKey2 = (bool)[[plist valueForKey:@&myKey2&] boolValue];
[plist setValue:myKey forKey:@&myKey&];
[plist writeToFile:path atomically:YES];
Show a simple alert with OK button.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:
@&An Alert!& delegate:self cancelButtonTitle:@&OK& otherButtonTitles:nil];
[alert show];
[alert release];
Info button
Increase the touchable area on the Info button, so it's easier to press.
CGRect newInfoButtonRect = CGRectMake(infoButton.frame.origin.x-25, infoButton.frame.origin.y-25, infoButton.frame.size.width+50, infoButton.frame.size.height+50);
[infoButton setFrame:newInfoButtonRect];
Detecting Subviews
You can loop through subviews of an existing view. This works especially well if you use the &tag& property on your views.
for (UIImageView *anImage in [self.view subviews])
if (anImage.tag == 1)
&&&&&&&&{ // do something }
已发表评论数()
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见
正文不准确
标题不准确
排版有问题
主题不准确
没有分页内容
图片无法显示
视频无法显示
与原文不一致转自Haven's blogiOS开发的这些年里,有的人用代码创建UI,有的人用xib创建UI。到底是用xib还是代码来创建UI,这个问题以前也有过很多争论,我只想说一点,各有各的优点。如果能够将两者融合贯通,那将是更有优势。笔者开发过程中,UI能用xib就尽量用xib(能用storyboard就用storyboard, 一个storyboard里最好别装太多的UIViewController,这在结队开发中将不利)。本文主要介绍使用xib的一些技术,即在xib中布局UI,然后xib与code相结合,快速UI开发介绍。本文主要讲解的也就是加载xib的技术。还是老方法,用代码说话,首先创建一个Single Page工程,命名为:LoadNibViewDemo。1.直接加载xib中的UIView创建一个View1.xib, 随便设一个背景色,加一个标识UILabel, 这样好知道是这个view是哪一个view. 你可以在这个view上加作意的subview,我只是说明原理,所以这儿并没有加作何subview. 最终我的View1如下图:由于View1会放到其它View上作为subview,所以这儿size是Freeform, Status Bar是:None。将下面代码放到viewDidLoad中://1&&NSArray&*views&=&[[NSBundle&mainBundle]&loadNibNamed:@&View1&&owner:nil&options:nil];&//&1&&UIView&*v&=&[views&lastObject];&&CGRect&r&=&v.&&r.origin.y&+=&80;&&v.frame&=&r;&&[self.view&addSubview:v];&&1这行代码就是加载View1.xib, 然后将xib中的UIView实保存到views中, 由于xib中我们只拖入了一个view, 所以这儿lastObject就返回这个view的实例,这样便加载了xib中的UIView. 接着将这个UIView addSubview到其它view上,运行效果如图:&2. 通过Owner建立变量关联首先我们为ViewController创建一个IBOutlet属性:@property&(nonatomic,&weak)&IBOutlet&UIView&*referencedV&接着同上面介绍的一样创建一个View2.xib, 如下图:File’s Owner中,我们设为ViewController, 这样我们就可以与实例变量_referencedView建立关联了,如图:接着在viewDidLoad中,在刚才加入的代码下面添加如下代码://&2&&[[NSBundle&mainBundle]&loadNibNamed:@&View2&&owner:self&options:nil];&&r&=&_referencedView.&&r.origin.y&=&v.frame.size.height&+&v.frame.origin.y;&&_referencedView.frame&=&r;&&[self.view&addSubview:_referencedView];&与//1中的代码有点类似,只不过owner属性为self了。这样一来,loadNibNamed后,就会实例化与之关联的变量_referencedView, 运行程序你将会看到效果:&3.Class Owner建立变量关联其实这个原理与上面2说的一样的,只不过这儿我们特别定义一个class来作为xib的Owner, 要所有需要关系的view都可以声明在这个Owner中,这样方便代码管理与维护。这里我们声明一个NSObject的子类FileOwner, 然后再在FileOnwer中声明IBOutLet的关联变量:@property&(nonatomic,&weak)&IBOutlet&UIView&*&同理创建一个View3.xib, File’s Owner设为FileOwner, 并建立view关联:&接着在viewDidLoad结尾处添加以下代码://&3&&FileOwner&*owner&=&[FileOwner&new];&&[[NSBundle&mainBundle]&loadNibNamed:@&View3&&owner:owner&options:nil];&&r&=&owner.view.&&r.origin.y&=&_referencedView.frame.origin.y&+&_referencedView.frame.size.&&owner.view.frame&=&r;&&[self.view&addSubview:owner.view];&运行效果:&&4. 引入UIView Category为了代码简单,我们增加一个UIView Category方法:+(id)loadFromNibNamed:(NSString*)&nibName&{&&&&&&return&[FileOwner&viewFromNibNamed:nibName];&&}&其中FileOwner的class 方法:+(id)viewFromNibNamed:(NSString*)&nibName&{&&&&&&FileOwner&*owner&=&[self&new];&&&&&&[[NSBundle&mainBundle]&loadNibNamed:nibName&owner:owner&options:nil];&&&&&&return&owner.&&}&这样加载xib的代码就会变得更简单。同理,我们创建一个View4.xib, File’s Owner设为FileOwner, 并建立view关联:接着在viewDidLoad尾添加代码://&4&&UIView&*v4&=&[UIView&loadFromNibNamed:@&View4&];&&r&=&v4.&&r.origin.y&=&owner.view.frame.origin.y&+&owner.view.frame.size.&&v4.frame&=&r;&&[self.view&addSubview:v4];&运行效果:&5. 自定义UIView类在4Category的基础上,我们再引入自定义UIView类,并在xib中与之关联。首先我们创建一个UIView字类UIView5。接着,我们创建一个View5.xib, File’s Owner设为FileOwner, 并建立view关联:&接着增加一个UIView的Category方法:+(id)loadFromNib&{&&&&&&return&[self&loadFromNibNamed:NSStringFromClass(self)];&&}&在viewDidLoad尾加入代码://&5&&View5&*v5&=&[View5&loadFromNib];&&r&=&v5.&&r.origin.y&=&v4.frame.origin.y&+&v4.frame.size.&&v5.frame&=&r;&&[self.view&addSubview:v5];&动行效果:&6.设置Onwer为UIViewController首先,我们创建一个View6.xib, File’s Owner设为UIViewController. 这样UIViewController的view属性关联我们xib中的UIView&&接着在viewDidLoad中添加代码://&6&&UIView&*v6&=&[[UIViewController&alloc]&initWithNibName:@&View6&&bundle:nil].&&r&=&v6.&&r.origin.y&=&v5.frame.origin.y&+&v5.frame.size.&&v6.frame&=&r;&&[self.view&addSubview:v6];&动行效果:&&说了这么多,是时候做一下总结了,其实其本是两个方法,一个是没有File’s Onwer直接加载xib中的UIView,二是通过File’s Onwer关联变量加载xib中的UIView。 然后就是一些Category提供简单接口而已。大家可以再细细品味一下上面所介绍的内容。大家可以看我源码中UIView+Ext的Category方法中还提供了一个方法:+ (id)loadFromNibNoO它应是方法5与方法1的组合,在此我就不细说了。 都是由上面两个基本方法演变出来的。7. xib link xib大家有没有想过在xib中link其它xib? 很可惜苹果不支持这个功能。但是我们可以通过一点技巧实现这个功能。下而我就简单介绍一下。先说一下原理,加载xib的UIView,如果这个UIView是自定义的UIView(即xib中关联了UIView的子类),如下图:&那么在加载显示这个view的时候会触发一些方法,如:-&(id)initWithCoder:(NSCoder&*)aDecoder&&-&(id)awakeAfterUsingCoder:(NSCoder*)aDecoder&我们就在这儿作些文章,在这儿用前面介绍的方法加载想要的的xib中UI实例替换掉原来返回的实例。首先我写了一个UIView的了类SubView,代码很容易理解:#import&&SubView.h&&#include&&UIView+Ext.h&&&@implementation&SubView&&-&(id)initWithFrame:(CGRect)frame&{&&&&&self&=&[super&initWithFrame:frame];&&&&&if&(self)&{&&&&&&&&&//&Initialization&code&&&&&}&&&&&return&&}&&&-&(id)&awakeAfterUsingCoder:(NSCoder*)aDecoder&{&&&&&BOOL&theThingThatGotLoadedWasJustAPlaceholder&=&([[self&subviews]&count]&==&0);&&&&&if&(theThingThatGotLoadedWasJustAPlaceholder)&{&&&&&&&&&SubView*&theRealThing&=&[[self&class]&loadFromNibNoOwner];&&&&&&&&&&&&&&&&//&pass&properties&through&&&&&&&&&[self&copyUIPropertiesTo:theRealThing];&&&&&&&&&&&&&&&&&&//auto&layout&&&&&&&&&self.translatesAutoresizingMaskIntoConstraints&=&NO;&&&&&&&&&theRealThing.translatesAutoresizingMaskIntoConstraints&=&NO;&&&&&&&&&&&&&&&&return&theRealT&&&&&}&&&&&return&&}&&-(void)&copyUIPropertiesTo:(UIView&*)view&{&&&&&//&reflection&did&not&work&to&get&those&lists,&so&I&hardcoded&them&&&&&//&any&suggestions&are&welcome&here&&&&&&&&&&NSArray&*properties&=&&&&&[NSArray&arrayWithObjects:&@&frame&,@&bounds&,&@&center&,&@&transform&,&@&contentScaleFactor&,&@&multipleTouchEnabled&,&@&exclusiveTouch&,&@&autoresizesSubviews&,&@&autoresizingMask&,&@&clipsToBounds&,&@&backgroundColor&,&@&alpha&,&@&opaque&,&@&clearsContextBeforeDrawing&,&@&hidden&,&@&contentMode&,&@&contentStretch&,&nil];&&&&&&&&&&//&some&getters&have&'is'&prefix&&&&&NSArray&*getters&=&&&&&[NSArray&arrayWithObjects:&@&frame&,&@&bounds&,&@&center&,&@&transform&,&@&contentScaleFactor&,&@&isMultipleTouchEnabled&,&@&isExclusiveTouch&,&@&autoresizesSubviews&,&@&autoresizingMask&,&@&clipsToBounds&,&@&backgroundColor&,&@&alpha&,&@&isOpaque&,&@&clearsContextBeforeDrawing&,&@&isHidden&,&@&contentMode&,&@&contentStretch&,&nil];&&&&&&&&&&for&(int&i=0;&i&[properties&count];&i++)&&&&&{&&&&&&&&&NSString&*&propertyName&=&[properties&objectAtIndex:i];&&&&&&&&&NSString&*&getter&=&[getters&objectAtIndex:i];&&&&&&&&&&&&&&&&&&SEL&getPropertySelector&=&NSSelectorFromString(getter);&&&&&&&&&&&&&&&&&&NSString&*setterSelectorName&=&&&&&&&&&[propertyName&stringByReplacingCharactersInRange:NSMakeRange(0,1)&withString:[[propertyName&substringToIndex:1]&capitalizedString]];&&&&&&&&&&&&&&&&&&setterSelectorName&=&[NSString&stringWithFormat:@&set%@:&,&setterSelectorName];&&&&&&&&&&&&&&&&&&SEL&setPropertySelector&=&NSSelectorFromString(setterSelectorName);&&&&&&&&&&&&&&&&&&if&([self&respondsToSelector:getPropertySelector]&&&&[view&respondsToSelector:setPropertySelector])&&&&&&&&&{&&&&&&&&&&&&&NSObject&*&propertyValue&=&[self&valueForKey:propertyName];&&&&&&&&&&&&&&&&&&&&&&&&&&[view&setValue:propertyValue&forKey:propertyName];&&&&&&&&&}&&&&&}&&&&&}&&@end&创建一个EmbeddedView.xib,我们想在其它xib中直接link这个EmbeddedView.xib, 还需要创建一个SubView的了类EmbeddedView。我的xib信息是这样的:一切就绪后,运行:&xib可以快速布署UI, 可以提高开发速度哦。 随便在此预告一下下一篇教程的内容:多Storyboard协作开发。终于这个教程写完了,完整的Demo可以在此下载:LoadNibViewDemo。希望大家多多支持,你们的支持将是我源源不断的动力。
最新教程周点击榜
微信扫一扫

我要回帖

更多关于 touchwiz主页是什么 的文章

 

随机推荐