【问题标题】:How to change the view height dynamically based on content size?如何根据内容大小动态更改视图高度?
【发布时间】:2016-06-23 13:56:51
【问题描述】:

我正在尝试向 contentView 添加两次 xib 文件,并且我想根据其中的内容大小更改 contentView 的高度。

这张图片显示了我想要实现的目标

这是我的代码

import UIKit

class ProfileSetViewController: UIViewController {

@IBOutlet weak var contentView: UIView!
@IBOutlet weak var contentViewHeight: NSLayoutConstraint!

override func viewDidLayoutSubviews() {

    if let CarViewAdd = NSBundle.mainBundle().loadNibNamed("CarViewAdd", owner: self, options: nil)[0] as? CarViewAdd {

        contentViewHeight.constant = 220
        contentView.frame.size.height = 220
        CarViewAdd.frame = CGRectMake(0, 0, self.contentView.frame.size.width, 220)
        CarViewAdd.carImage.layer.cornerRadius = 10
        CarViewAdd.carImage.clipsToBounds = true
        CarViewAdd.carImage.layer.borderColor = UIColor(red: 255/255, green: 0/255, blue: 0/255, alpha: 1.0).CGColor
        CarViewAdd.carImage.layer.borderWidth = 3
        contentView.addSubview(CarViewAdd)

    }

    if let CarViewAdd = NSBundle.mainBundle().loadNibNamed("CarViewAdd", owner: self, options: nil)[0] as? CarViewAdd {

        contentViewHeight.constant = 442
        contentView.frame.size.height = 442
        CarViewAdd.frame = CGRectMake(0, 222, self.contentView.frame.size.width, 220)
        CarViewAdd.carImage.layer.cornerRadius = 10
        CarViewAdd.carImage.clipsToBounds = true
        CarViewAdd.carImage.layer.borderColor = UIColor(red: 255/255, green: 0/255, blue: 0/255, alpha: 1.0).CGColor
        CarViewAdd.carImage.layer.borderWidth = 3
        contentView.addSubview(CarViewAdd)
    }

}

这是我得到的结果。

请注意顶部的 xib 图片显示不正确。我该如何解决这个问题?

【问题讨论】:

    标签: swift uiview autolayout


    【解决方案1】:

    我通过为每个 xib 添加一个带有 xib 文件所需框架的 UIView 来解决此问题,然后我将 xib 添加到具有相同高度和宽度的 UIView。

    【讨论】:

      【解决方案2】:

      尝试改变 carImage.contentMode = .ScaleAspectFit

      【讨论】:

      • carImage 内容模式在情节提要中设置为纵横比填充。我什至尝试过适合方面,但我没有修复它。
      猜你喜欢
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 2021-07-03
      • 2012-01-06
      相关资源
      最近更新 更多