swift - UIView 不从 xib 文件 Swift 调整大小

标签 swift xcode uiview storyboard xib

我已经创建了一个包含 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 的 XIB 文件 XIB File for the specialist banner view

xib 文件中的标签 Label inside the xib file

xib 中的药丸 View Pill View within the xib

在 View Controller 中使用 xib View 的 Storyboard文件 Storyboard file using the xib view inside of a view controller

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/

相关文章:

ios 使用自动布局在另一个 View 中放置 3 个 View

ios - 检测何时将我的 UIView 子类添加到另一个 UIView

swift - transform.scale 上的 CABasicAnimation 在 X 和 Y 轴上平移 CAShapeLayer

ios - 从 sqlite 表获取数据时出现问题

ios - Swift 2 - 定期从 slider 打印新值

xcode - 我应该在 SVN 中提交 .xcodeproj 文件吗?

xcode - 如何使用lldb "memory find"命令?

uiviewcontroller - 使用 Swift 从一个 ViewController 滑动到另一个

ios - CoreData执行后台任务冲突

objective-c - 使用自动布局自定义纵横比