【问题标题】:How to set borderColor of `UISegmentControl` in `swift`?如何在`swift`中设置`UISegmentControl`的borderColor?
【发布时间】:2021-01-22 20:38:25
【问题描述】:

在问这个问题之前,我已经搜索了stackoverflow,找到了一个相关的帖子:

change segmentControl border color

但我们可以看到它是objective-c 语言。

那么我们怎样才能改变UISegmentControlswift中的borderColor呢?

【问题讨论】:

    标签: ios swift uisegmentedcontrol


    【解决方案1】:

    更简单的方法:

    segmentControl.layer.borderWidth = 1.0
    segmentControl.layer.cornerRadius = 5.0
    segmentControl.layer.borderColor = UIColor.red.cgColor
    segmentControl.layer.masksToBounds = true
    

    【讨论】:

      【解决方案2】:

      您只需将代码转换为 swift...

      let customSegmentedControl = UISegmentedControl.appearance()    
      customSegmentedControl.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.red], for: UIControlState.normal)
      

      但我相信您发布的代码会改变字母的实际颜色,而不是外面的颜色。外面的颜色叫做“tint”,它的变化是这样的:

      customSegmentedControl.tintColor = UIColor.blue
      

      编辑:仅用于更改边框

      由于 SegmentedControl 中的每个段都是一个实际的 UIView,因此您可以直接访问它们并根据您的需要自定义它们,如 this answer

      或者您可以设置我认为可以设置为您需要的颜色的“背景图片”。 (虽然上面的方法看起来不那么复杂)

      【讨论】:

      • 不好意思混淆了,我只是想把边框颜色改成灰色。
      • 边框颜色为灰色但内部保持橙色?和白色的字母?
      • 对,只是想改变边框颜色,你知道,set tint color边框颜色也会被设置。
      【解决方案3】:

      添加插座

      @IBOutlet weak var customSegment: UISegmentedControl!
      

      然后在你的 viewDidload 方法中

          customSegment.layer.borderWidth = 1.0
          customSegment.layer.cornerRadius = 5.0
          customSegment.layer.borderColor = UIColor.red.cgColor
          customSegment.layer.masksToBounds = true
      

      【讨论】:

        【解决方案4】:

        我们可以设置背景图片来实现效果。

            let customSegmentedControl = UISegmentedControl.appearance()
            //customSegmentedControl.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.red], for: UIControlState.normal)
        
            customSegmentedControl.setBackgroundImage(UIImage.init(named: "ni2.png"), for: .normal, barMetrics: .default)
            customSegmentedControl.setBackgroundImage(UIImage.init(named: "ni.png"), for: .selected, barMetrics: .default)
        

        【讨论】:

          【解决方案5】:
          self.segementControl.layer.borderWidth = 0.3
          self.segementControl.layer.cornerRadius = 3.0
          self.segementControl.layer.borderColor = UIColor.orange.cgColor
          

          【讨论】:

            猜你喜欢
            • 2023-03-05
            • 1970-01-01
            • 1970-01-01
            • 2014-06-02
            • 2011-10-14
            • 1970-01-01
            • 2019-05-19
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多