首页 > 解决方案 > How to add a custom view from a xib to a UIScrollView?

问题描述

Problem

I am trying to add a custom view from a xib into a UIScrollView.

I added a UIScrollView to an empty ViewController in my storyboard. I also added 4 constraints for leading, trailing, top, bottom to Safe Area and set them all Equal to 0.

Now in the code I want to add a custom view "EquipmentInfoView" to the existed UIScrollView

class EquipmentInfoVC: UIViewController {
    @IBOutlet var scrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        equipmentInfoView = EquipmentInfoView.instantiate()
        scrollView.addSubview(equipmentInfoView)
    }
}

And it does not work as the ScrollView does not scroll. How should I do it instead?

Here is the custom view "EquipmentInfoView"

class EquipmentInfoView: UIView {

    @IBOutlet var nameTextView: UITextView!
    @IBOutlet var descriptionTextView: UITextView!
    @IBOutlet var equipmentImageView: UIImageView!

    static func instantiate() -> EquipmentInfoView {
        let view: EquipmentInfoView = initFromNib()
        return view
    }
}

Extra Notes

I know this is not the normal way to create a custom view from xib. However, this way I dont have to set the File's Owner to "EquipmentInfoView", instead I set the View's Custom Class to "EquipmentInfoView". (Setting File's Owner to "EquipmentInfoView" gives me EXC_BAD_ACCESS when I do unit testing)

For clarity, this is how I would add this view to a normal (non-scroll) view:

equipmentInfoView = EquipmentInfoView.instantiate()
mainView.addSubview(equipmentInfoView)
equipmentInfoView.frame = mainView.bounds
equipmentInfoView.autoresizingMask = [.flexibleHeight, .flexibleWidth]

标签: swiftuiscrollviewxibnib

解决方案


您可能缺少 scrollView 的 contentSize

class EquipmentInfoVC: UIViewController {
    @IBOutlet var scrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        equipmentInfoView = EquipmentInfoView.instantiate()
        scrollView.contentSize = equipmentInfoView.frame.size
        scrollView.addSubview(equipmentInfoView)
    }
}

推荐阅读