swift - 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]
解决方案
您可能缺少 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)
}
}
推荐阅读
- php - 如何使用 phpmailer 处理数百个收件人
- python - 有没有办法按第二列从最大值到最小值对数组进行排序?
- ios - 当 'a' 应该是返回的值时,'a+1' 被保存
- automapper - 如何展开属性,在其他地图中被忽略?
- tkinter - Tkinter 打开和关闭顶层窗口
- node.js - 如何从json中的firestore返回数据?
- c++ - 如何使用 std::find 从 vector< pair < string, string >> type 的第一个元素中查找字符串?
- qt - QMenu 中的 QIcon 不会通过鼠标悬停或单击来更改图像
- r - 无法加载 xlsx 包
- excel - 如何使用 VBA vlookup 函数填写多列数据?