gpt4 book ai didi

ios - 将 Xib 加载到 UIView 中而不将其添加为 subview

转载 作者:行者123 更新时间:2023-11-28 09:28:32 24 4
gpt4 key购买 nike

如何将 nib 加载到 UIView 而不必将其添加为 subview?在 objc 中,您可以在 init 方法中执行 self = [NSBundle MainBundle].loadNibNamed... 但 swift 说 “无法在方法中分配给‘self’”

enter image description here

在 Object 中你可以做到这一点。 Reusable Views但似乎 swift 不喜欢它。我发现的唯一方法是将 Xib 加载到 UIView 并将其添加为当前 View 的 subview

@IBDesignable class CustomViewFromXib: UIView 
{
var nibName: String = "CustomViewFromXib"
override init(frame: CGRect)
{
super.init(frame: frame)
setup()
}
required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
setup()
}

func setup()
{
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
view.frame = bounds
self.view.addSubview(view)
}
}

最佳答案

[[NSBundle mainBundle] loadNibNamed:@"myNib"owner:self options:nil];

是另一种方式来设置它的所有者。

它有点滑,可能会破坏事物的 KVO/KVC 方面

关于ios - 将 Xib 加载到 UIView 中而不将其添加为 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29579815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com