作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
这是我用 Swift 编写的 UISegmentedControl
:
我用下面的代码创建了它:
let selectedAttributes: NSDictionary = [
NSForegroundColorAttributeName: UIColor.black,
NSFontAttributeName: fontForSegmentedControl!
]
let normalAttributes: NSDictionary = [
NSForegroundColorAttributeName: UIColor.gray,
NSFontAttributeName: fontForSegmentedControl!
]
mySegmentedControl.setTitleTextAttributes(selectedAttributes as [NSObject : AnyObject], for: UIControlState.selected)
mySegmentedControl.setTitleTextAttributes(normalAttributes as [NSObject : AnyObject], for: UIControlState.normal)
删除边框的扩展在这里:
extension UISegmentedControl {
func removeBorders() {
setBackgroundImage(imageWithColor(color: UIColor.white/*backgroundColor!*/), for: .normal, barMetrics: .default)
setBackgroundImage(imageWithColor(color: tintColor!), for: .selected, barMetrics: .default)
setDividerImage(imageWithColor(color: UIColor.clear), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
}
// 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!
}
}
但是它有一个问题。
当我点击(并按住)ONE
或 TWO
时,它会将背景颜色更改为此(当它被用户手指触摸时):
我缺少一些用于更改 UISegmentedControl
中选定(临时按下)选项样式的代码。
如何删除深灰色选区并保留清晰的颜色?
最佳答案
与您已经为 UIControlState.normal
设置背景图像的方式类似,您需要为 UIControlState.highlighted
和 UIControlState.selected< 设置适当的图像
+ UIControlState.highlighted
.
将以下代码添加到您的扩展函数 removeBorders()
(假设您希望为按下的未选定段设置清晰的背景,为按下的选定段设置浅色背景):
setBackgroundImage(imageWithColor(color: .clear), for: .highlighted, barMetrics: .default)
setBackgroundImage(imageWithColor(color: tintColor!), for: [.selected, .highlighted], barMetrics: .default)
关于ios - 当用户在 Swift 中选择 UISegmentedControl 时,如何更改它的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42425629/
我是一名优秀的程序员,十分优秀!