在 swift 中更改段开关上的段控件标题颜色

Change Segment Control Title Color on segment switch in swift

我有一个视图控制器,我在上面有段控制,我在滑动手势上切换段,现在我希望当我切换段时,当前段标题颜色应该变成白色,其余颜色应该变成灰色,我已经搜索过了关于它,但我得到了背景颜色更改的结果,如何在段之间切换时更改段控件标题颜色?这是我的滑动分段代码,

 let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red]
    segmentControl.setTitleTextAttributes(titleTextAttributes, for: .selected)
    segmentControl.fallBackToPreIOS13Layout(using: UIColor.clear)
    let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.swipedRight))
    swipeRight.direction = UISwipeGestureRecognizer.Direction.right
    self.activeView.addGestureRecognizer(swipeRight)

    let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.swipedLeft))
    swipeLeft.direction = UISwipeGestureRecognizer.Direction.left
    self.closedView.addGestureRecognizer(swipeLeft)

 @objc func swipedRight(){
    segmentControl.selectedSegmentIndex = 0
    self.activeView.isHidden = false
    self.closedView.isHidden = true
    let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
    segmentControl.setTitleTextAttributes(titleTextAttributes, for: .selected)
    let titleText = [NSAttributedString.Key.foregroundColor: UIColor.gray]
    segmentControl.setTitleTextAttributes(titleText, for: .disabled)

    getActiveQuestionAPI()
}

@objc func swipedLeft(){
    segmentControl.selectedSegmentIndex = 1
    self.activeView.isHidden = true
    self.closedView.isHidden = false
    let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
    segmentControl.setTitleTextAttributes(titleTextAttributes, for: .selected)
    let titleText = [NSAttributedString.Key.foregroundColor: UIColor.gray]
    segmentControl.setTitleTextAttributes(titleText, for: .disabled)

    getCloseQuestionAPI()
}

要检查段控制值何时更改,您可以使用这样的 addTarget 方法。

segmentControl.addTarget(self, action: #selector(onSegmentedControlValueChanged(_:)), for: .valueChanged)

然后像以前的方法一样实施 onSegmentedControlValueChanged

@objc func onSegmentedControlValueChanged(_ sender: UISegmentedControl) {
  // Do something when segment control value changes
}

要更改段控件的标题文本,您实际上不必检查值何时更改,只需通过以下代码片段即可实现:

let titleTextAttributesForSelected = [NSAttributedString.Key.foregroundColor: UIColor.white]
let titleTextAttributesForNormal = [NSAttributedString.Key.foregroundColor: UIColor.black]
segmentControll.setTitleTextAttributes(titleTextAttributesForSelected, for: .selected)
segmentControll.setTitleTextAttributes(titleTextAttributesForNormal, for: .normal)

这就是更改不同状态的段控件标题颜色所需的全部内容。