iOS视图

iOS 自定义xib及在xib、storyboard中使用

2022-06-22  本文已影响0人  落寞绅士

在实际开发中经常遇到项目中有相同样式的视图,我们就可以自定义一个xib视图在不同的地方使用。demo传送门custom-xib-example

1.新建一个继承UIView的类,例如HLCustomView

2.新建一个xib,取名和1中的类名一致HLCustomView.xib

3.【重点】:关联类和xib,选中xib,选中File's OwnerClassHLCustomView

图片.png

4.在HLCustomView.h中加入IB_DESIGNABLE

IB_DESIGNABLE

@interface HLCustomView : UIView

@end

5.在HLCustomView.m中加入一下代码(也可以将这段代码加成Xcode代码块)

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self build];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        [self build];
    }
    return self;
}

#pragma mark - Private Mehtod

- (void)build
{
    UIView *view = nil;
#if TARGET_INTERFACE_BUILDER
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    view = [[bundle loadNibNamed:NSStringFromClass(self.class) owner:self options:nil] firstObject];
#else
    view = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:self options:nil] firstObject];
#endif
    view.frame = self.bounds;
    [self addSubview:view];
}

6.在xib、storyboard中使用。拖一个View将Class改为HLCustomView即可

图片.png
demo传送门custom-xib-example
上一篇下一篇

猜你喜欢

热点阅读