问题就在这里:
let shadowView = UIView( frame: CGRect( x: -10, y: -20, width: (view.frame.width+20), height: 90 ) )
您正在对框架进行硬编码 -
不要这样做!将高度设置为90是可以的,但是
x: -10, y: -20, width: (view.frame.width+20)
非常糟糕。并非所有手机都具有相同的尺寸。
从技术上讲,您可以根据
NoeOnJupiter
的评论计算安全区域插图高度,但这仍然不太好。当用户旋转设备并且刘海移动时会发生什么?听起来很麻烦。
您需要的是
自动布局和
安全区域。使用自动布局,只需定义一些约束条件,就可以在所有屏幕尺寸下轻松实现漂亮的
UIView
。然后,安全区域定义了屏幕上哪些部分是“安全”的,意味着“不被刘海或圆角屏幕遮挡”。
因此,您可以将
shadowView
固定到屏幕边缘(超出刘海/安全区域),并添加
.systemGreen
背景颜色。然后,使
titleView
高度为90点,并在垂直方向上将其固定到
shadowView
上。请注意
titleView.topAnchor
如何固定到
shadowView.safeAreaLayoutGuide.topAnchor
- 这使其远离刘海。
let shadowView = UIView()
shadowView.translatesAutoresizingMaskIntoConstraints = false
shadowView.backgroundColor = .systemGreen
shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOpacity = 0.3
shadowView.layer.shadowOffset = CGSize(width: 5, height: 3)
shadowView.layer.shadowRadius = 4.0
shadowView.layer.cornerRadius = 45
shadowView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
view.addSubview(shadowView)
let titleView = UIView()
titleView.translatesAutoresizingMaskIntoConstraints = false
shadowView.addSubview(titleView)
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleView.addSubview(titleLabel)
titleLabel.text = "Catalogues"
titleLabel.font = UIFont.systemFont(ofSize: 36, weight: .medium)
NSLayoutConstraint.activate([
shadowView.topAnchor.constraint(equalTo: view.topAnchor),
shadowView.rightAnchor.constraint(equalTo: view.rightAnchor),
shadowView.leftAnchor.constraint(equalTo: view.leftAnchor),
titleView.topAnchor.constraint(equalTo: shadowView.safeAreaLayoutGuide.topAnchor),
titleView.heightAnchor.constraint(equalToConstant: 90),
titleView.rightAnchor.constraint(equalTo: shadowView.rightAnchor),
titleView.leftAnchor.constraint(equalTo: shadowView.leftAnchor),
titleView.bottomAnchor.constraint(equalTo: shadowView.bottomAnchor),
titleLabel.centerXAnchor.constraint(equalTo: titleView.centerXAnchor),
titleLabel.centerYAnchor.constraint(equalTo: titleView.centerYAnchor)
])
结果:
iPhone 8 |
iPhone 12 |
|
|
如需进一步阅读,我有一篇关于这个主题的博客文章。