如何使用 xib 创建自定义视图
Posted
技术标签:
【中文标题】如何使用 xib 创建自定义视图【英文标题】:how to create a custom view using xib 【发布时间】:2019-06-12 12:20:03 【问题描述】:我创建了一个可以在多个地方重用的自定义视图,我已经将这个类名分配给视图控制器的子视图。这里我完全使用 XIB 的。在运行这个应用程序时它会崩溃并出现错误“线程 1:EXC_BAD_ACCESS (code=2, address=0x7ffeee23be2c)" 在 "Bundle.main.loadNibNamed("TripCancelAlert", owner: self, options: nil)" 行
查看类:
class TripCancelAlert: UIView
override init(frame: CGRect)
super.init(frame: frame)
commonInit()
required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)
commonInit()
func commonInit()
Bundle.main.loadNibNamed("TripCancelAlert", owner: self, options: nil)
// self.addSubview(contentView)
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
*/
【问题讨论】:
可能是medium.com/@umairhassanbaig/…可以帮你做到这一点。 Thankyou..Seriously 这个链接对我帮助很大。 【参考方案1】:在超类下方找到您的视图。
请务必将您的xib
命名为与您的class
相同的名称(MyView.xib / MyView
)
class NibView: UIView
@IBOutlet var view: UIView!
required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)
commonInit()
override init(frame: CGRect)
super.init(frame: frame)
commonInit()
func commonInit()
guard let viewFromNib = Bundle.main.loadNibNamed(className, owner: self, options: nil)?.first as? UIView
else fatalError("Could not load view from nib file.")
view = viewFromNib
translatesAutoresizingMaskIntoConstraints = false
view.translatesAutoresizingMaskIntoConstraints = false
addPinnedSubview(view)
func addPinnedSubview(_ view: UIView, withInsets insets: UIEdgeInsets = .zero)
addSubview(view)
let viewsDict: [String: UIView] = ["childView": view]
var metrics: [String: Any] = [:]
metrics["topSpace"] = insets.top
metrics["bottomSpace"] = insets.bottom
metrics["leftSpace"] = insets.left
metrics["rightSpace"] = insets.right
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(topSpace)-[childView]-(bottomSpace)-|",
options: [],
metrics: metrics,
views: viewsDict))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(leftSpace)-[childView]-(rightSpace)-|",
options: [],
metrics: metrics,
views: viewsDict))
【讨论】:
以上是关于如何使用 xib 创建自定义视图的主要内容,如果未能解决你的问题,请参考以下文章
如何从 XIB 文件加载自定义创建的视图并添加到 StackView