Это известный хак для изменения цвета оттенка UISegmentedControl
.
let sortedViews = listSegmentedControl.subviews.sorted( by: { $0.frame.origin.x < $1.frame.origin.x } )
for (index, view) in sortedViews.enumerated() {
if index == listSegmentedControl.selectedSegmentIndex {
view.tintColor = UIColor(patternImage: gradientImage)
} else {
view.tintColor = UIColor.gray //Whatever the color of non selected segment controller tab
}
}
Хотя это выглядит как уродливый хак, я использую его довольно давно и кажется довольно простым. Надеюсь, поможет.
ИЗМЕНИТЬ:
Это то, что тебе нужно, приятель?
Если да, дайте мне знать, я опубликую код для того же.
ИЗМЕНИТЬ 2:
Как OP упомянул в своем комментарии, что ожидаемый результат такой же, как тот, который я показал на изображении выше, предоставляя код для того же.
Отказ от ответственности:
Как упоминал rmaddy в своих комментариях ниже, это хак и использует недокументированный (хотя и полный общедоступный API), но очень известный хак для изменения цвета оттенка UISegemntedControl, который существует еще с iOS 5 (вот как я помню, дай мне знать, если я ошибаюсь)
Поэтому используйте ответ с осторожностью, поскольку в будущих выпусках iOS Apple может изменить структуру подпредставлений в UISegemntedControl
и может повлиять на ваш O/P. Ничего из того, что я вижу, не приведет к сбою, но может повлиять на то, как O/P отображается на экране.
Я объявил переменную, чтобы GradientImage можно было сгенерировать только один раз, но ваша реализация может использовать ее так, как вы хотите.
var gradientImage : UIImage! = nil
В ViewDidLoad
я инициализирую gradientImage
и UISegmentedControl
как
override func viewDidLoad() {
super.viewDidLoad()
gradientImage = gradient(size: segmentControl.frame.size, color: [UIColor.black, UIColor.red])!
//I have specified custom font need not necessarily be used
//Font color attribute is important though, usually `UISegementedControl` title takes color from tint color, because we might need a different color for text to highlight above gradient color am using custom font colors
let font = UIFont(name: "HelveticaNeue-Medium", size: 20)
segmentControl.setTitleTextAttributes([NSFontAttributeName : font!, NSForegroundColorAttributeName : UIColor.blue], for: .normal)
segmentControl.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.white], for: .selected)
//Set the border color and border to `UISegmentedControl` and also make it round corner
segmentControl.layer.borderColor = UIColor(patternImage: gradientImage).cgColor
segmentControl.layer.borderWidth = 2
segmentControl.layer.masksToBounds = true
segmentControl.layer.cornerRadius = 10
//In order to update the selected Segment tint and background color we need to call multiple statements every time selection changes hence I have moved it to the function and called it in viewDidLoad
updateGradientBackground()
}
Наконец, определение функции updateGradientBackground такое же, как и в моем исходном ответе.
fileprivate func updateGradientBackground() {
let sortedViews = segmentControl.subviews.sorted( by: { $0.frame.origin.x < $1.frame.origin.x } )
for (index, view) in sortedViews.enumerated() {
if index == segmentControl.selectedSegmentIndex {
//very important thing to notice here is because tint color was not honoring the `UIColor(patternImage` I rather used `backgroundColor` to create the effect and set clear color as clear color
view.backgroundColor = UIColor(patternImage: self.gradientImage)
view.tintColor = UIColor.clear
} else {
//very important thing to notice here is because tint color was not honoring the `UIColor(patternImage` I rather used `backgroundColor` to create the effect and set clear color as clear color
view.backgroundColor = UIColor.white //Whatever the color of non selected segment controller tab
view.tintColor = UIColor.clear
}
}
}
Наконец, в IBAction UISegmentedControl просто вызовите
@IBAction func segmentControllerTapped(_ sender: UISegmentedControl) {
self.updateGradientBackground()
}
Надеюсь это поможет
person
Sandeep Bhandari
schedule
02.07.2018