iOS 用xib自定义View

  网上有很多关于实现用xib自定义View,那我为什么还要写呢?第一,我用他们的方法都没有实现。第二,用xib遇到了很多问题,想分享给大家。

用xib自定义View:FHCustomView

1.新建UIView
FHCustomView.png
2.建一个同名xib : FHCustomView.xib

新建xib(1).png

新建xib(2).png
3.配置FHCustomView.xib

xib配置.png
注意:(1)只需要配置View ->Class 为FHCustomView就可以了,以前我把File’s Ower ->Class也配置为FHCustomView了,结果在iOS7中闪退,按钮的点击的方法报unrecognized selector sent to instance 0x1741df770错误,闪退。不用配置File‘s Ower ->Class!
4.重写initWithFrame方法
FHCustomView.m

#import "FHCustomView.h"

@implementation FHCustomView

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    self = [[[NSBundle mainBundle] loadNibNamed:@"FHCustomView" owner:self options:nil] lastObject];
    if (self) {
        self.frame = frame;
    }
    return self;
}
@end

  到这里,用xib自定义View就结束了,是不是感觉很简单。确实很简单,但是我也踩过很多坑。如果配置File’s Ower ->Class,在iOS9、iOS10中都没问题,但是iOS7就会闪退。由于一开始没有iOS7的测试机,我一直没办法定位到问题出现在哪里。个人建议昂,如果刚开始接触iOS开发,最好别用xib。虽然上手容易,不过还是有很多坑,出了问题不好定位,而且只要出问题就是闪退,容错率太低,用户体验不好。

posted @ 2017-04-28 14:57  豆丶浆油条  阅读(505)  评论(1编辑  收藏  举报