2017-02-23 147 views
11

這是我UISegmentedControl寫在斯威夫特:當用戶在Swift中選擇UISegmentedControl時,如何更改它的樣式?

enter image description here

我用下面的代碼創建它:

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! 
    } 
} 

但有一件事是錯誤的。

當我點擊(並按住)ONETWO它改變了背景色爲這個(爲它被用戶的手指觸摸時):

enter image description here

我錯過了一些代碼更改UISegmentedControl中選定(臨時按下)選項的樣式。

我該如何去除暗灰色的選擇並使其保持清晰的顏色?

回答

9

如何您已經設置背景圖片爲UIControlState.normal類似,您需要爲UIControlState.highlightedUIControlState.selected + UIControlState.highlighted設置適當的圖像。

下面的代碼添加到您的擴展功能removeBorders()(假設你想爲按未選擇段中的清晰的背景和壓制選定一個色調彩色背景):

setBackgroundImage(imageWithColor(color: .clear), for: .highlighted, barMetrics: .default) 
setBackgroundImage(imageWithColor(color: tintColor!), for: [.selected, .highlighted], barMetrics: .default) 
+0

我試過了,它幾乎工作:)現在當用戶按下當前沒有選擇的選項 - 它不會突出顯示爲灰色,但是 - 仍然有可能按下當前選中的選項並將背景更改爲灰色 - 您知道我該如何修復它? – user3766930

+1

@ user3766930當然,你可以做到,我更新了答案。 –

0
let normalAttributes: NSDictionary = [ 
    NSForegroundColorAttributeName: UIColor.gray, 
    NSFontAttributeName: fontForSegmentedControl! 
] 

mySegmentedControl.setTitleTextAttributes(selectedAttributes as [NSObject : AnyObject], for: UIControlState.selected) 

上面的代碼只加灰色的選擇,所以改變它像下面

let normalAttributes: NSDictionary = [ 
    NSForegroundColorAttributeName: UIColor.white, 
    NSFontAttributeName: fontForSegmentedControl! 
] 

mySegmentedControl.setTitleTextAttributes(selectedAttributes as [NSObject : AnyObject], for: UIControlState.selected) 
相關問題