Swift - 在 class 中为自己分配一个 NIB

Swift - Assign a NIB to self in class

我正在为通知下拉横幅创建 UIView 子class。 我正在使用 XIB 构建视图,并希望在初始化时将该 xib 分配给 class(即避免通过调用 ViewController 执行此操作)。

由于您无法在 swift 中分配给 'self',我如何从 class 本身中正确地执行此操作?

class MyDropDown: UIView
{
     func showNotification()
     {
          self = UINib(nibName: nibNamed, bundle: bundle).instantiateWithOwner(nil, options: nil)[0] as? UIView
     }
}

我通常的做法是:

  1. 将我的 custom-view class 设置为 FileOwner in the nib
  2. 设置所有需要的出口和行动
  3. 将 outlet 设置为 nib 中的视图,并在 class
  4. 中将其命名为 'contentView'
  5. init* 方法中 - 用所有者实例化 nib 并将子视图添加到我的 custom-view object.

这里是 collection header 视图的示例,以这种方式实现。

@interface Header : UITableViewHeaderFooterView

@property (nonatomic) IBOutlet UIView *contentView;

@property (weak, nonatomic) IBOutlet UILabel *labelTitle;
// other required outlets & actions
// ... 

@end


#import "Header.h"

@implementation Header

- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
        [[NSBundle mainBundle] loadNibNamed:@"Header"
                                      owner:self
                                    options:nil];
        [self.contentView addSubview:self.content];

        UIView *subview = self.content;
        self.content.translatesAutoresizingMaskIntoConstraints  = NO;
        NSDictionary *viewsDictionary =  NSDictionaryOfVariableBindings(subview);
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[subview]|" options:0 metrics: 0 views:viewsDictionary]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[subview]|" options:0 metrics: 0 views:viewsDictionary]];

    }
    return self;
}

@end

// 更新 Swift 示例

主要思想不是直接从 nib 加载视图到 self,而是将它/view from nib/ 作为子视图添加到 self

import UIKit

class CustomView: UIView {

    @IBOutlet var contentView: UIView!
    @IBOutlet weak var labelTitle: UILabel!

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.__loadContent()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.__loadContent()
    }

    private func __loadContent() {
        // create nib
        let nib = UINib(nibName: "CustomView", bundle: NSBundle.mainBundle())
        // load outlets to self
        nib.instantiateWithOwner(self, options: nil)
        // add content view as a subview
        self.addSubview(self.contentView)
        // disable autoresizing
        self.contentView.setTranslatesAutoresizingMaskIntoConstraints(false)
        // manually create constraints to fix content view inside self with 0 padding
        let viewsDict: NSDictionary = ["content": self.contentView]
        let vertical = NSLayoutConstraint.constraintsWithVisualFormat("V:|[content]|",
            options: NSLayoutFormatOptions.allZeros,
            metrics: nil,
            views: viewsDict)
        let horizontal = NSLayoutConstraint.constraintsWithVisualFormat("H:|[content]|",
            options: NSLayoutFormatOptions.allZeros,
            metrics: nil, views: viewsDict)
        self.addConstraints(vertical)
        self.addConstraints(horizontal)
    }
}

对于正在寻找如何从 swift 中自己的 class 初始化 xib 的任何人,这里是使用自定义 class 初始化程序的最佳方法:

class MyCustomView: UIView
{
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!

    class func initWithTitle(title: String, image: UIImage? = nil) -> MyCustomView
    {
        var myCustomView = UINib(nibName: "MyCustomView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as? MyCustomView

        myCustomView.titleLabel.text = title

        if image != nil
        {
            myCustomView.imageView.image = image
        }

        //...do other customization here...
        return myCustomView
    }
}