从.xib文件加载自定义UIView时,线程1 EXC_BAD_ACCESS

时间:2019-07-17 11:09:46

标签: swift uiview uiscrollview xib nib

我试图将多个自定义UIViews从.xib文件加载到UIScrollView中,但我不断收到“线程1:EXC_BAD_ACCESS”。

由于这是我第一次真正尝试加载自定义UIView(对UICollectionView和UITableView单元进行了很多次),因此我一直在关注此tutorial

class PreSignupDataQuestionView : NibView
{
    @IBOutlet weak var vMainContainer: UIView!
    @IBOutlet weak var vQuestionViewContainer: UIView!
    @IBOutlet weak var ivQuestionViewImage: UIImageView!
    @IBOutlet weak var lblQuestion: UILabel!
}

class NibView : UIView
{
    var view: UIView!

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

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

private extension NibView
{
    func xibSetup()
    {
        backgroundColor = UIColor.clear
        view = loadNib()
        view.frame = bounds
        addSubview(view)

        view.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[childView]|",
                                                      options: [],
                                                      metrics: nil,
                                                      views: ["childView": view!]))
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[childView]|",
                                                      options: [],
                                                      metrics: nil,
                                                      views: ["childView": view!]))
    }
}

extension UIView
{
    func loadNib() -> UIView
    {
        let bundle = Bundle(for: type(of: self))
        let nibName = type(of: self).description().components(separatedBy: ".").last!
        let nib = UINib(nibName: nibName, bundle: bundle)

        // Error pops here
        return nib.instantiate(withOwner: self, options: nil).first as! UIView
    }
}

在UIViewController中,我有一个设置UIScrollView的函数,在我尝试加载自定义UIView之前,它可以正常工作。

for index in 0..<self.screenData.count
{
    let xCoordinate = (CGFloat(index) * (width)) + firstSpace
    let viewFrame = CGRect(x: xCoordinate, y: 0, width: width - spaceBetweenView, height: height)

    let childView = PreSignupDataQuestionView().loadNib() as! PreSignupDataQuestionView

    childView.frame = viewFrame
    childView.tag = index
    childView.isUserInteractionEnabled = true

    childView.ivQuestionViewImage.image = UIImage(named: "PlaceholderImage")
    childView.lblQuestion.text = "Lorep Ipsum"
    self.svQuestions.addSubview(childView)
}

但是,如果不涉及.xib,我可以轻松加载UIView:

let xCoordinate = (CGFloat(index) * (width)) + firstSpace + lastSpace
let viewFrame = CGRect(x: xCoordinate, y: 0, width: width - spaceBetweenView, height: height)
let childView = UIView()
childView.tag = index
childView.isUserInteractionEnabled = true

if index % 2 == 0 { childView.backgroundColor = .red }
else { childView.backgroundColor = .green }

childView.frame = viewFrame
self.scrollView.addSubview(childView)

有什么想法吗?我一直在尝试将自定义UIView加载到UIScrollView中一段时间​​,似乎无法弄清楚。 我知道这是一个普遍的问题,但到目前为止对我来说没有任何帮助。

1 个答案:

答案 0 :(得分:1)

该教程不太正确...

通过代码加载自定义视图-PreSignupDataQuestionView-时,请更改以下行:

let childView = PreSignupDataQuestionView().loadNib() as! PreSignupDataQuestionView

简单地说:

let childView = PreSignupDataQuestionView()

应该照顾它。


编辑:

在新的视图控制器中尝试此操作,以排除其他可能的问题:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let childView = PreSignupDataQuestionView()

        childView.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(childView)

        NSLayoutConstraint.activate([
            childView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 100),
            childView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 50),
            childView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -50),

            childView.heightAnchor.constraint(equalToConstant: 300),

            ])

    }

}

编辑2:

我在https://github.com/DonMag/XIBLoadExtension上发布了完整的示例项目

查看是否适合您。如果是这样,请与您所需要的进行比较,以了解有什么不同。