Por*_*ner 7 uisegmentedcontrol swift
开始学习Swift并尝试转换此ObjectiveC代码:
[[mySegmentedControl.subviews objectAtIndex:0] setTintColor:[UIColor blueColor]]
Run Code Online (Sandbox Code Playgroud)
这可以正确设置第一个段的色调.
这是我最接近获得相同代码的Swift版本:
mySegmentedControl?.subviews[0].tintColor = UIColor.blueColor()
Run Code Online (Sandbox Code Playgroud)
我得到的错误是 '@Ivalue $T9' is not identical to 'UIColor!!'
我不明白这个错误意味着什么.当我查看.tintColor它列出的方法时UIColor!?,我还没有找到!?Swift中的共同意义.
Pra*_*tha 19
这将解决您的问题:
var subViewOfSegment: UIView = mySegmentedControl.subviews[0] as UIView
subViewOfSegment.tintColor = UIColor.blueColor()
Run Code Online (Sandbox Code Playgroud)
你也可以
(mySegmentedControl.subviews[0] as UIView).tintColor = UIColor .blueColor()
Run Code Online (Sandbox Code Playgroud)
小智 11
我找到的最简单的方法是:
segmentControl.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.redColor()], forState: UIControlState.Selected)
Run Code Online (Sandbox Code Playgroud)
此代码适用于 2019 年 8 月的最新版本 Swift (Swift 3.0)
这里我实现的这段代码是对 Segment 控件的扩展,可以用于应用程序中的所有段控件,其中代码集必须在应用程序类中定义。
扩展方法可以直接在应用程序中使用,也可以将所有设置添加到扩展类中的相同方法或不同方法中,如下所示。
extension UISegmentedControl {
func setSegmentStyle() {
setBackgroundImage(imageWithColor(color: backgroundColor!), for: .normal, barMetrics: .default)
setBackgroundImage(imageWithColor(color: tintColor!), for: .selected, barMetrics: .default)
setDividerImage(imageWithColor(color: UIColor.clear), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
let segAttributes: NSDictionary = [
NSForegroundColorAttributeName: UIColor.gray,
NSFontAttributeName: UIFont(name: "System-System", size: 14)!
]
setTitleTextAttributes(segAttributes as [NSObject : AnyObject], for: UIControlState.selected)
}
// create a 1x1 image with this color
private func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor);
context!.fill(rect);
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image!
}
}
Run Code Online (Sandbox Code Playgroud)
以下代码可以用于段的任何地方
self.mySegment.setSegmentStyle()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22354 次 |
| 最近记录: |