Swift 中 iOS 的自定义分段控件
Custom Segmented Control in Swift for iOS
我正在尝试实现一个分段控件,但它的布局看起来很简单。我要定制:
- 例如去掉边框
- 有自定义指标
有什么方法可以做到?我在 Android 中知道如何自定义 TabLayout,但老实说,我在这里不知所措。
如果我需要自定义的内容不在此列表中,UISegmentedControl Docs,我会自己构建。
在您的图像中,我会使用两个按钮、一个指示器视图和一些响应用户交互的逻辑。
我来晚了,但我会这样做:
将背景颜色设置为.clear
segmentedControlInstance.backgroundColor = UIColor(red:0.13, green:0.16, blue:0.29, alpha:1.0)
将背景色设置为.clear
segmentedControlInstance.tintColor = .clear
我注意到所选片段的标题是粗体。为两种状态(.normal & .selected)设置文本属性
segmentedControlInstance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 16)], for: .normal)
segmentedControlInstance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 16)], for: .selected)
最后,设置两张背景图。注意,我不知道要为 barMetrics 参数设置什么:
segmentedControlInstance.setBackgroundImage(UIImage(name: "selectedSegment", for: .selected, barMetrics: ?)
segmentedControlInstance.setBackgroundImage(UIImage(name: "normalSegment", for: .normal, barMetrics: ?)
我将让您尝试使用 barMetrics 参数。
我正在尝试实现一个分段控件,但它的布局看起来很简单。我要定制:
- 例如去掉边框
- 有自定义指标
有什么方法可以做到?我在 Android 中知道如何自定义 TabLayout,但老实说,我在这里不知所措。
如果我需要自定义的内容不在此列表中,UISegmentedControl Docs,我会自己构建。
在您的图像中,我会使用两个按钮、一个指示器视图和一些响应用户交互的逻辑。
我来晚了,但我会这样做:
将背景颜色设置为.clear
segmentedControlInstance.backgroundColor = UIColor(red:0.13, green:0.16, blue:0.29, alpha:1.0)
将背景色设置为.clear
segmentedControlInstance.tintColor = .clear
我注意到所选片段的标题是粗体。为两种状态(.normal & .selected)设置文本属性
segmentedControlInstance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 16)], for: .normal)
segmentedControlInstance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 16)], for: .selected)
最后,设置两张背景图。注意,我不知道要为 barMetrics 参数设置什么:
segmentedControlInstance.setBackgroundImage(UIImage(name: "selectedSegment", for: .selected, barMetrics: ?)
segmentedControlInstance.setBackgroundImage(UIImage(name: "normalSegment", for: .normal, barMetrics: ?)
我将让您尝试使用 barMetrics 参数。