我正在尝试复制类似 Tinder 的菜单,在 UIScrollView
中使用 3 个 UIViewControllers
,在顶部有一个自定义菜单选项卡,每个 都有一个按钮>UIViewController
。我面临一个有趣的问题,UIViewControllers
View 完全适合 scrollView.frame,但仅适用于 iPhone 8。相比之下,对于 iPhone SE,它留下了一个白色边距,对于 iPhone 8+,它似乎与 scrollView.view 中的 View 重叠。有人可以解释为什么会发生这种情况以及我该如何解决吗?
这是我在 UIScrollView
中调整设置 UIViewControllers
的代码:
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var navigationView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
setUpHorizontalScrollViews()
}
func setUpHorizontalScrollViews(){
let view = (
x: self.view.bounds.origin.x,
y: self.view.bounds.origin.y,
width: self.view.bounds.width,
height: self.view.bounds.height
)
let scrollWidth = 3 * view.width
let scrollHeight = view.height
scrollView.contentSize = CGSize(width: scrollWidth, height: scrollHeight)
scrollView.contentOffset.x = view.x
if let messagesView = self.storyboard?.instantiateViewController(withIdentifier: "MessagesVC") as UIViewController! {
self.addChildViewController(messagesView)
self.scrollView.addSubview(messagesView.view)
messagesView.didMove(toParentViewController: self)
messagesView.view.frame = CGRect(x: 0,
y: 0,
width: view.width,
height: view.height
)
}
if let friendsView = self.storyboard?.instantiateViewController(withIdentifier: "FriendsVC") as UIViewController! {
self.addChildViewController(friendsView)
self.scrollView.addSubview(friendsView.view)
friendsView.didMove(toParentViewController: self)
friendsView.view.frame = CGRect(x: view.width,
y: 0,
width: view.width,
height: view.height
)
}
if let settingsView = self.storyboard?.instantiateViewController(withIdentifier: "SettingsVC") as UIViewController! {
self.addChildViewController(settingsView)
self.scrollView.addSubview(settingsView.view)
settingsView.didMove(toParentViewController: self)
settingsView.view.frame = CGRect(x: 2 * view.width,
y: 0,
width: view.width,
height: view.height
)
}
// offset to the second view
self.scrollView.contentOffset.x = view.width
}
override var shouldAutorotate: Bool {
return false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
这是我的安装程序的样子。顶部是 MainViewController,包含 UIScrollView
,底部是应该进入 scrollView 的 3 个 View Controller 。
这就是我想要的样子,以及它在 iPhone 8 中的设置方式:
这是它在 iPhone SE 上的样子以及我的问题所在:
最佳答案
问题在于,由于您在 viewDidLoad()
中调用了 setUpHorizontalScrollViews
方法,因此 UIViewController 还没有对 subview 进行布局,也没有计算它们的最终大小。
它可以在 iPhone 8 中运行,因为最有可能证明它的屏幕尺寸与您在界面构建器中使用的屏幕尺寸相同。
解决方案一
为了解决这个问题,您可以将您的代码移动到viewDidAppear()
方法中。但是,一旦您打开 UIViewController(除非您添加全屏加载),这将导致丑陋的效果。
方案二
像这样添加 view.layourIfNeeded()
:
override func viewDidLoad() {
super.viewDidLoad()
view.layourIfNeeded()
setUpHorizontalScrollViews()
}
关于swift - UIViewController 未在所有 iPhone 的 UIScrollView 中正确调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49059761/