【问题标题】:Change Segment Control Title Color on segment switch in swift快速更改段开关上的段控制标题颜色
【发布时间】:2019-11-01 00:24:06
【问题描述】:

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

 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()
}

【问题讨论】:

    标签: ios swift uisegmentedcontrol


    【解决方案1】:

    要检查段控制值何时更改,您可以使用addTarget 方法,如下所示。

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

    然后只需像以前的方法那样实现onSegmentedControlValueChanged

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

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

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

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

    【讨论】:

    • 谢谢老哥知道了,现在工作正常。 @Luka Cefarin
    猜你喜欢
    • 1970-01-01
    • 2020-10-27
    • 2022-11-04
    • 1970-01-01
    • 2019-08-18
    • 2015-11-29
    • 2011-06-07
    • 1970-01-01
    • 2012-08-19
    相关资源
    最近更新 更多