我要在(半透明)导航栏的正下方添加一个分段控件,并希望它具有相同的颜色。我试图使其看起来像是导航栏的一部分。
isOpaque = false
layer.opacity = 0.85
let bkImg = UIImage(color: .systemBackground.withAplhaComponent(0.85), size: CGSize(width: 1, height: 16))
segmentedCtrl.setBackgroundImage(bkImg, for: .normal, barMetrics: .default)
setDividerImage(bkImg, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
我尝试过使用分段控件的不透明度和的颜色bkImg
,但这根本没有效果。从头开始编写自定义选项卡栏会更快-iOS 13中的分段控件无法自定义。
这是一个完全hack,但看起来不错。
class CustomSegmentedControl: UISegmentedControl {
private var underline: UIView!
init() {
super.init(frame: .zero)
underline = UIView()
underline.backgroundColor = tintColor
view.addSubvie(underline)
}
override func layoutSubviews() {
super.layoutSubviews()
// Set background color to match navigation bar
let bgColor = UIColor.systemBackground.hsbComponents.brightness == 1.0
? UIColor.black.withAlphaComponent(0.028) // light
: UIColor.white.withAlphaComponent(0.073) // dark
let img = UIImage(color: bgColor, size: CGSize(width: 1, height: 16))
setBackgroundImage(img, for: .normal, barMetrics: .default)
setDividerImage(img, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
// Bonus: underline below selected tab
var frame = underline.frame
let tabWidth = self.frame.width / CGFloat(numberOfSegments)
frame.origin.x = CGFloat(selectedSegmentIndex) * tabWidth
frame.origin.y = self.frame.height - 2.0
frame.size.width = tabWidth
underline.frame = frame
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句