IOS 使用XIB 自定义View

一般自定义View       代码方式 有

      在初始化的时候添加 子Views

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // add subviews
    }
    return self;
}

还有种 是自己画。 重载   

- (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  跟平常就不一样了  因为  不是我们来  实例化它     

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

 

+(LKTextView *)instanceTextView
{
    NSArray* nibView =  [[NSBundle mainBundle] loadNibNamed:@"LKTextView" owner:nil options:nil];
    return [nibView objectAtIndex:0];
}

如果你要加点什么东西  就重载 initWithCoder 

 

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
        //you init
    }
    return self;
}


使用的方法:

LKTextView* text = [LKTextView instanceTextView];
    text.frame = CGRectMake(100, 100, text.frame.size.width, text.frame.size.height);
    text.textView.text = @"input ";
   [self.view addSubview:text];
原文地址:https://www.cnblogs.com/sunfuyou/p/6880729.html