【问题标题】:Swift - Assign a NIB to self in classSwift - 在课堂上为自己分配一个 NIB
【发布时间】:2015-03-27 21:12:58
【问题描述】:

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

由于您无法快速分配给“self”,我如何在类本身中正确执行此操作?

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

【问题讨论】:

    标签: ios swift subclass xib init


    【解决方案1】:

    对于任何想在 swift 中从它自己的类初始化 xib 的人,这里是使用自定义类初始化器的最佳方法:

    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
        }
    }
    

    【讨论】:

      【解决方案2】:

      我通常的做法是:

      1. 在笔尖中将我的自定义视图类设置为FileOwner
      2. 设置所有必需的出口和操作
      3. 在 nib 中为视图设置 outlet 并在类中将其命名为 'contentView'
      4. init* 方法中 - 使用所有者实例化 nib 并将子视图添加到我的自定义视图对象。

      这是以这种方式实现的集合标题视图的示例。

      @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 示例

      主要思想不是将视图从笔尖直接加载到self,而是将它/视图从笔尖/作为子视图添加到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)
          }
      }
      

      【讨论】:

      • 你的方法是针对objective-c的。在 swift 中,init 方法不返回对象,并且 'self' 不可赋值。
      • 我的方法与语言无关。您可以参与 if(){...} 并迅速使用它。问题是 - 您没有将视图从 nib 分配给 self,而是将其作为子视图添加到 self。
      • 请查看 swift 示例。
      • 非常感谢!这将使我的生活更轻松!
      猜你喜欢
      • 1970-01-01
      • 2016-08-02
      • 2019-01-14
      • 2022-12-09
      • 2020-06-26
      • 2014-02-10
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多