我已经创建了一个包含 UIView 的 xib 文件。我在 Storyboard中使用这个 View ,并希望它根据其中的内容调整大小。当我在 Storyboard中明确设置 View 的高度时,它与 XIB 文件的高度相同。每个手机屏幕似乎也具有相同的 xib 高度和宽度,这会导致 View 离开屏幕,无论我将约束设置在 Storyboard 内是什么。
我试过隐藏 View 并将横幅的高度设置为 35
self.specialistBanner.pillView.isHidden = true
specialistBannerHeight.constant = 35
我试过了
specialistBannerHeight.constant = 35
让 Storyboard中的 View 变小
我也试过
self.specialistBanner.sizeToFit()
没用
在 View Controller 中使用 xib View 的 Storyboard文件
class SpecialistBannerView: UIView {
@IBOutlet weak var bannerTitle: UILabel!
@IBOutlet weak var pillView: PillCollectionView!
var viewModel = SpecialistBannerViewModel()
// Initialize xib
let SpecialistBannerView = "SpecialistBannerView"
override func awakeFromNib() {
super.awakeFromNib()
self.translatesAutoresizingMaskIntoConstraints = false
}
override init(frame: CGRect) {
super.init(frame: frame)
initXib(view: self)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initXib(view: self)
}
func initXib(view: SpecialistBannerView) {
let viewToShow = Bundle.main.loadNibNamed(SpecialistBannerView, owner: self, options: nil)?[0] as? UIView ?? UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.sizeToFit()
view.addSubview(viewToShow)
view.frame = view.bounds
view.pillView.setUp()
view.sizeToFit()
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
viewModel.specialistBannerViewProtocol = self
}
任何帮助将不胜感激
最佳答案
我遇到了你同样的问题。我在另一个问题中找到了答案。 您必须在自定义 View 中覆盖 LayoutSubViews() 并设置边界
override func layoutSubviews() {
super.layoutSubviews()
// we need to adjust the frame of the subview to no longer match the size used
// in the XIB file BUT the actual frame we got assinged from the superview
self.view.frame = self.bounds
}
关于swift - UIView 不从 xib 文件 Swift 调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48528677/