StoryBoard中使用xib

转自:http://blog.csdn.net/li6185377/article/details/8131042


一般自定义View       代码方式 有

      在初始化的时候添加 子Views

  1. - (id)initWithFrame:(CGRect)frame  
  2. {  
  3.     self = [super initWithFrame:frame];  
  4.     if (self) {  
  5.         // add subviews  
  6.     }  
  7.     return self;  
  8. }  

还有种 是自己画。 重载   

- (void)drawRect:(CGRect)rect {

}

如果  布局复杂的话  这种代码方式  可以郁闷死人   看不到效果,慢慢调 ,代码冗长。。。  所以可以用到 XIB 来进行布局。

  UIViewController   是我以前用的法子    但是  我只是想用到 View    用个View 每次都还要跟个Controller 。 还要保存他  不让他被释放  。。。    

 

所以嘞  我找了个新方法   使用XIB 但不使用ViewController 当他的载体 let go

在你项目中 新建个 类   继承UIView


在新建个XIB   XIB 的名称要跟 你新建 类名 一样


在XIB 中 选中View  改它Class 为你建的 类名


 然后  你就可以在上面拖来拖去     就按ViewController 中的来就是    你可以发现 IBOUT 中 Object  变成了  你的类

 

 

最后 改下 View 的Autosizing 项

 

要使用这个UIView  跟平常就不一样了  因为  不是我们来  实例化它     

平常我就通过 这个静态方法 来实例化

 

  1. +(LKTextView *)instanceTextView  
  2. {  
  3.     NSArray* nibView =  [[NSBundle mainBundle] loadNibNamed:@"LKTextView" owner:nil options:nil];  
  4.     return [nibView objectAtIndex:0];  
  5. }  
如果你要加点什么东西  就重载 initWithCoder 

 

  1. -(id)initWithCoder:(NSCoder *)aDecoder  
  2. {  
  3.     self = [super initWithCoder:aDecoder];  
  4.     if(self)  
  5.     {  
  6.         //you init  
  7.     }  
  8.     return self;  
  9. }  

使用的方法:
  1. LKTextView* text = [LKTextView instanceTextView];  
  2.     text.frame = CGRectMake(100, 100, text.frame.size.width, text.frame.size.height);  
  3.     text.textView.text = @"input ";  
  4.    [self.view addSubview:text];  
原文地址:https://www.cnblogs.com/jz319/p/3972530.html