将视图从XIB添加到自定义UINavigationBar子类

时间:2016-03-24 08:39:06

标签: ios swift uiview uinavigationbar

我跟着this code创建了一个更高的UINavigationBar:

var heightIncrease: CGFloat = 38.0

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.transform = CGAffineTransformMakeTranslation(0, -heightIncrease)
}

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

override func sizeThatFits(size: CGSize) -> CGSize {
    var newSize = super.sizeThatFits(size)
    newSize.height += heightIncrease
    return newSize
}

override func layoutSubviews() {
    super.layoutSubviews()
    for view in self.subviews {
        if (NSStringFromClass(view.classForCoder).containsString("UINavigationBarBackground")) {
            view.frame.origin.y = self.bounds.origin.y + heightIncrease - statusBarHeight
            view.frame.size.height = self.bounds.size.height + statusBarHeight
        }
    }
}

var statusBarHeight: CGFloat {
    return UIApplication.sharedApplication().statusBarFrame.size.height
}

enter image description here

现在我想从XIB添加一个视图到底部。我的第一个想法是做这样的事情:

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

    self.transform = CGAffineTransformMakeTranslation(0, -heightIncrease)

    if let accessoryView = NSBundle.mainBundle()
        .loadNibNamed("NavBarAccessoryView", owner: self, options: nil)
        .first as? NavBarAccessoryView {
            accessoryView.frame.size.width = self.bounds.size.width
            accessoryView.frame.origin.y = 75
            self.addSubview(accessoryView)
    }
}

看起来没问题,但是我无法在分段控件中选择一个细分,就像它只是一张图片一样:

enter image description here

有更好的方法吗?对不起,如果这是一个愚蠢的问题,或者我的尝试毫无意义,我是新手,到目前为止,我只处理了界面构建者的观点和内容。< / p>

1 个答案:

答案 0 :(得分:0)

我写扩展名:

extension UIView {

static func instanceFromNibByClassName()  -> UIView {
    let nibName = stringFromClass(self as AnyClass)
    return NSBundle.mainBundle().loadNibNamed(nibName, owner: nil, options: nil).first! as! UIView
}

}

所以我可以得到这样的实例:

    var coverTableViewCell=YQEventCoverTableViewCell.instanceFromNibByClassName() as! YQEventCoverTableViewCell