2017-11-29 17 views
0

私はiOSのコンポーネント・ベースのシステムを作成しようとしている、と私は次の操作を実行したいと思います:xibsを使用した入れ子の@IBDesignables?

  1. 任意の追加の子コンポーネントの周りの空間の8pxを持っている「PaddedView」コンポーネントを作成し、コンテナ型コンポーネントのように。

  2. ストーリーボードのこのPaddedViewに別のIBDesignableビューを追加し、両方のレンダーを表示します。

これは可能ですか?

今、私はxibsから自分の意見をロードするために、すべてのIBDesignableコンポーネントについて、次のスーパークラスを使用しています:

import Foundation 
import UIKit 

@IBDesignable 
class SKDesignableView: UIView { 
    var view: UIView? 

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

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

    func loadXib() { 
     self.view = self.viewFromXib() 
     self.view!.frame = self.bounds 
     self.view!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] 
     self.addSubview(self.view!) 
    } 

    func viewFromXib() -> UIView { 
     let bundle = UINib(nibName: String(describing: self.getType()), bundle: Bundle(for: self.getType())) 
     let views = bundle.instantiate(withOwner: self, options: nil) 
     return views.first as! UIView 
    } 

    func getType() -> AnyClass { 
     fatalError() 
    } 
} 

は、どのように私は他のIBDesignablesのプレースホルダを作成するのですか?

答えて

0

ビューには最初は子が含まれているため、子ビューを必要とするコンポーネントには、コンテナビューをサブビューとして追加します。

func loadXib() { 
     var subview: UIView? = nil 
     if self.subviews.count > 0 { 
      subview = self.subviews[0] 
     } 
     subview?.removeFromSuperview() 

     self.view = self.viewFromXib() 
     self.view!.frame = self.bounds 
     self.view!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] 

     if let subview = subview { 
      let lConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, 
        toItem: self.view!, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 8) 
      let rConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, 
        toItem: self.view!, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: -8) 
      let tConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, 
        toItem: self.view!, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 8) 
      let bConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, 
        toItem: self.view!, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -8) 
      self.view!.addSubview(subview) 
      self.view!.addConstraints([lConstraint, rConstraint, tConstraint, bConstraint]) 
     } 
     self.addSubview(self.view!) 
    } 

このアプローチは、複数のサブビューを追加するタグなどで一般化できます。

関連する問題