我有一个视图控制器,在该控制器上我具有片段控制,并且我可以通过滑动手势切换片段,现在我希望当我切换片段时,当前片段标题颜色应变为白色,而其余颜色应变为灰色,我已经进行了搜索但是我得到了背景颜色更改的结果,如何在各段之间切换时更改段控件标题颜色?这是我的滑动代码片段,
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()
}
答案 0 :(得分:2)
要检查段控制值何时发生变化,可以使用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)
这是为不同状态更改段控件标题颜色所需的全部内容。