Currently, I am implementing custom view from a xib with Content View
size set to Freeform
. Here is my Content View hierarchy
Although the Content View is Freeform, I set the width to 375, which is the same width with iPhone 8. Then I create a custom UIView file
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
Bundle.main.loadNibNamed("DetailsWeather", owner: self, options: nil)
addSubview(contentView)
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
After that, I set the xib File’s Owner
custom class name to the same custom UIView file above. Then I implement it into Main.storyboard
by adding a UIView, set constrains properly and give it the custom class name the same with File’s Owner
When running iPhone 8, everything is perfect but switching to smaller device like iPhone 5s, I notice my scroll view now have horizontal scroll. Contrast with iPhone 5s, the bigger screen device like iPhone 8+, my scroll view now lost a bit of to the right side.
Notice the labels does not align with the clock which is center on iP8+ anymore
So I tried to remove the scroll view and everything work normal across devices. So from these, I was thinking the scroll view must messed up my custom view. Then I do some self research and found out these topics.
How to update constraints after adding UIView from xib on UIScrollView in swift?
ScrollView Add SubView in swift 3
I tried their solution and modified to fit my situation but none of them seem to work with me. So my question is, is there a way to make Content View of a xib file to fit every width?
Just solved today, feels great tbh
File’s Owner
custom class name and replace Content View
custom class name to the same name with your custom UIViewMain.storyboard
, my case is ScrollView. Add all required constrains (duh)@IBOutlet weak var scrollView: UIScrollView!
let alohaView = Bundle.main.loadNibNamed("Feature", owner: self, options: nil)?.first as? FeatureView
with Feature
is your xib file and FeatureView
is your custom UIView file control that xib filealohaView?.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 500)
notice I hardcode the 500 height, will work more on thisscrollView.contentSize = CGSize(width: self.view.frame.size.width, height: (alohaView?.frame.size.height)!)
scrollView.addSubview(alohaView!)
add the custom view back to scroll view