我有一个视图控制器,在其上我具有片段控制,并且我可以通过滑动手势切换片段,现在我希望当我切换片段时,当前片段标题颜色应变为白色,而其余颜色应变为灰色,我已经进行了搜索,但是我得到了背景颜色更改的结果,如何在段之间切换时更改段控件标题颜色?这是我的细分代码,
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()
}
。disabled设置了灰色的前景色属性。您应该为状态。normal设置该值。请尝试如下设置。normal状态。
let titleText = [NSAttributedString.Key.foregroundColor: UIColor.gray]
segmentControl.setTitleTextAttributes(titleText, for: .normal)
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)
这是更改不同状态的段控件标题颜色所需的全部。