【问题标题】:Swift 4 - UIView frame shows false sizeSwift 4 - UIView 框架显示错误大小
【发布时间】:2018-06-26 19:13:54
【问题描述】:

我有一个透明的 UIView。此视图称为“ma​​inView

我想向 ma​​inView 添加一个相同大小的子视图。 所以,我在 mainView 类本身中初始化它https://i.stack.imgur.com/pz6Ql.png 它看起来像这样:[https://i.stack.imgur.com/Y8MEr.png] 这正是我想要的!

但是假设我删除了这段代码,并且我想在我的 UIViewController 中初始化一个子视图:https://i.stack.imgur.com/aCpWf.png 我创建了 ma​​inView 的出口并使用边界进行初始化mainView 的一个 subView。

不幸的是,我的视图现在看起来像这样:https://i.stack.imgur.com/stekd.png 但是您可以在上面的代码中看到我将框架正确设置为视图的框架 ma​​inView.bounds

您能解释一下为什么新视图(子视图)的大小与我在 ma​​inView 类 本身中初始化它时的大小不同吗?

【问题讨论】:

  • 您需要edit 将您的代码作为文本包含在您的问题中,而不是作为图像链接。
  • 为什么?代码图片是不是更简单?
  • 没有。无法搜索到图片链接的代码,无法引用它们,它们使问题更难阅读,这是最好的部分 - 将实际代码复制并粘贴到您的问题中比截屏和截屏要简单得多上传图片。
  • 首先,永远不要在Draw() 中创建/添加子视图——这会被多次调用,你最终会得到很多重复的按钮。其次,使用自动布局和约束而不是显式设置框架...视图的框架未在viewDidLoad() 中设置,这就是它不匹配的原因。使用自动布局可以解决这个问题,加上“自动”会在超级视图更改(例如旋转设备)时更改它。
  • @DonMag 您说“视图的框架未在viewDidLoad() 中设置。但是当我在加载 mainView 后设置框架时,它仍然具有相同的“假”大小。@IBOutlet weak var mainView: MainView! { didSet { let newView = UIView(frame: mainView.bounds) newView.backgroundColor = UIColor.green mainView.addSubview(newView) } }

标签: ios swift uiview uiviewcontroller swift4


【解决方案1】:

如果你学会了如何使用自动布局,你会好很多。

override func viewDidLoad() {
    super.viewDidLoad()

    // create the view
    let newView = UIView()
    // we want to use auto-layout
    newView.translatesAutoresizingMaskIntoConstraints = false
    // set the view's background color
    newView.backgroundColor = .green

    // add the new view to the "main" view
    view.addSubview(newView)

    // constrain top / bottom / leading / trailing anchors
    newView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    newView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    newView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    newView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

    // the newView will now have the same frame as the "main" view, and its
    // frame will auto-adjust if the main view changes (such as on device rotate)
}

【讨论】:

  • 谢谢。您说“视图的框架未在'viewDidLoad'中设置,然后在哪里设置?
  • 这里有几个不错的答案:stackoverflow.com/questions/5562938/… ...本质上,自动布局可以在加载/初始化/显示阶段进行多次“通过”。另外,考虑一下视图何时改变大小?框架不能可能在 viewDidLoad() 中设置为其“完成状态”,因为在应用程序运行时可以随时旋转设备。举个例子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-09
  • 2012-03-13
  • 1970-01-01
相关资源
最近更新 更多