【问题标题】:Match UISegmentedControl's color with that of translucent navigation bar将 UISegmentedControl 颜色与半透明导航栏颜色匹配
【发布时间】:2020-08-05 02:01:28
【问题描述】:

我在(半透明)导航栏正下方添加了一个分段控件,并希望它具有相同的颜色。我试图让它看起来像是导航栏的一部分。

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 中的分段控件无法自定义。

【问题讨论】:

  • 我记得我为最近的一个项目努力寻找一个好的解决方案,最后我改用了BetterSegmentedControl Framework,它允许大量自定义,如果可以选择框架,请尝试一下。跨度>

标签: ios swift ios13 uisegmentedcontrol


【解决方案1】:

这完全是 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
    }
}

【讨论】:

    【解决方案2】:

    此效果可以通过将UISegmentedControl 放在UIToolbar 内,并将UIToolbar 定位在UINavigationBar 下方来实现。一旦进入UIToolbar,UISegmentedControl 就会呈现与UINavigationBar 相同的外观。

    如果您希望UIToolBar 融入UINavigationBar,您需要将所有与UINavigationBar 相同的外观选项应用于UIToolBar(例如barTintColor 和@987654333 @)。

    我不知道如何调整 UISegmentedControl 本身以模仿导航栏和工具栏应用的外观,但使用此策略我们不需要。

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-24
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多