我通常喜欢在界面生成器中创建和设计uiviews。有时我需要在xib中创建一个视图,该视图可以在情节提要中的多个视图控制器中重复使用。
我通常喜欢在界面生成器中创建和设计uiviews。有时我需要在xib中创建一个视图,该视图可以在情节提要中的多个视图控制器中重复使用。
Answers:
经过Swift 2.2和Xcode 7.3.1测试

//  DesignableXibView.swift
import UIKit
@IBDesignable
class DesignableXibView: UIView {
    var contentView : UIView?
    override init(frame: CGRect) {
        super.init(frame: frame)
        xibSetup()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        xibSetup()
    }
    func xibSetup() {
        contentView = loadViewFromNib()
        // use bounds not frame or it'll be offset
        contentView!.frame = bounds
        // Make the view stretch with containing view
        contentView!.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
        // Adding custom subview on top of our view (over any custom drawing > see note below)
        addSubview(contentView!)
    }
    func loadViewFromNib() -> UIView! {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: String(self.dynamicType), bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
        return view
    }
}

在Xcode 6.3.1中工作
创建一个名为“ ReuseableView”的新UIView
创建一个名为“ ReuseableView”的匹配XIB文件
设置xib的文件所有者
在身份检查器中将自定义类设置为“ ReusableView”。 

从ReuseableView.xib中的视图向您的ReuseableView.h界面添加一个插座

添加initWithCoder实现以加载视图并添加为子视图。
- (id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        // 1. load the interface
        [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
        // 2. add as subview
        [self addSubview:self.view];
        // 3. allow for autolayout
        self.view.translatesAutoresizingMaskIntoConstraints = NO;
        // 4. add constraints to span entire view
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics:nil views:@{@"view":self.view}]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:@{@"view":self.view}]];
    }
    return self;
}

在情节提要中测试您的可重用视图

跑步观察!

UINib(nibName: nibName, bundle: nil).instantiateWithOwner(nil, options: nil)它比NSBundle-Version更快。
                    @IBDesignable on the class.还必须实现init(frame:)-但除此之外,它还可以很好地工作!  supereasyapps.com/blog/2014/12/15/…–
                    Swift 3&4更新为接受的答案
1.创建一个名为“ DesignableXibView”的新UIView
2.创建一个名为“ DesignableXibView”的匹配xib文件
3.设置xib的文件所有者
选择“ DesignableXibView.xib”>“文件的所有者”,然后在身份检查器中将“自定义类”设置为“ DesignableXibView”。
4. DesignableXibView的实现
    import UIKit
@IBDesignable
class DesignableXibView: UIView {
    var contentView : UIView!
    override init(frame: CGRect) {
        super.init(frame: frame)
        xibSetup()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        xibSetup()
    }
    func xibSetup() {
        contentView = loadViewFromNib()
        // use bounds not frame or it'll be offset
        contentView.frame = bounds
        // Make the view stretch with containing view
        contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
        // Adding custom subview on top of our view 
        addSubview(contentView)
    }
    func loadViewFromNib() -> UIView! {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
        return view
    }
} 
5在情节提要中测试您的可重用视图
打开故事板
新增检视
设置该视图的自定义类别
DesignableXibView。生成项目以查看更改。
                    String(describing: type(of: self))应该安全地执行此操作
                    如果有人在翻译它时遇到麻烦,请使用swift 2中的initWithCoder函数:
required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        UINib(nibName: String(self.dynamicType), bundle: NSBundle.mainBundle()).instantiateWithOwner(self, options: nil)
        self.addSubview(view)
        self.view.translatesAutoresizingMaskIntoConstraints = false
        self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: NSLayoutFormatOptions.AlignAllCenterY , metrics: nil, views: ["view": self.view]))
        self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: NSLayoutFormatOptions.AlignAllCenterX , metrics: nil, views: ["view": self.view]))
    }
仅仅转换Swift为Objective-C不足以使其正常工作。我很难允许在Storyboard中进行实时渲染。
翻译完整个代码后,在设备(或模拟器)上运行时,视图加载良好,但Storyboard中的实时渲染不起作用。这是因为我使用了[NSBundle mainBundle]Interface Builder却无法访问mainBundle。您必须使用的是[NSBundle bundleForClass:self.classForCoder]。BOOM,实时渲染现已开始!
注意:如果您在使用自动版面配置时遇到问题,请尝试Safe Area Layout Guides在Xib中禁用。
为了方便起见,我将整个代码留在此处,以便您只需复制/粘贴(对于所有过程,请遵循原始答案):
BottomBarView.h
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface BottomBarView : UIView
@end
BottomBarView.m
#import "BottomBarView.h"
@interface BottomBarView() {
    UIView *contentView;
}
@end
@implementation BottomBarView
-(id) initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self xibSetup];
    }
    return self;
}
-(id) initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self xibSetup];
    }
    return self;
}
-(void) xibSetup {
    contentView = [self loadViewFromNib];
    contentView.frame = self.bounds;
    contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self addSubview:contentView];
}
-(UIView*) loadViewFromNib {
    NSBundle *bundle = [NSBundle bundleForClass:self.classForCoder]; //this is the important line for view to render in IB
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:bundle];
    UIView *view = [nib instantiateWithOwner:self options:nil][0];
    return view;
}
@end
告诉我,如果您遇到一些问题,但应该可以立即使用:)
如果有人感兴趣,这是@Garfbargle步骤4的Xamarin.iOS版本
public partial class CustomView : UIView
    {
        public ErrorView(IntPtr handle) : base(handle)
        {
        }
        [Export("awakeFromNib")]
        public override void AwakeFromNib()
        {
            var nibObjects = NSBundle.MainBundle.LoadNib("CustomView", this, null);
            var view = (UIView)Runtime.GetNSObject(nibObjects.ValueAt(0));
            view.Frame = Bounds;
            view.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            AddSubview(rootView);
        }
    }
这就是您一直想要的答案。您可以只创建您的CustomView类,并在xib中将其主实例包含所有子视图和出口。然后,您可以将该类应用于情节提要或其他xib中的任何实例。
无需摆弄文件所有者,或将插座连接到代理服务器或以特殊方式修改xib,或将自定义视图的实例添加为其自身的子视图。
只是这样做:
UIView为NibView(或从更改UITableViewCell为NibTableViewCell)而已!
它甚至可以与IBDesignable一起使用,以在设计时在情节提要中呈现您的自定义视图(包括来自xib的子视图)。
您可以在此处了解更多信息:https : //medium.com/build-an-app-like-lego/embed-a-xib-in-a-storyboard-953edf274155
您可以在此处获取开源的BFWControls框架:https : //github.com/BareFeetWare/BFWControls
汤姆👣