Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selected state of text in a segmented control in Xcode

I am working on my first application using Swift and Xcode.

In one of my views, I have a segmented control which has emoticons as the text being displayed. However, I have a problem where whenever one of the emoticons is selected, it becomes blacked out as shown in the image below:

segmentedControl

I think the problem has to do with the text attributes of the selected state of my segmented control, and my attempt at a fix was setting the text attributes of the selected state to be the same as the text attributes of the normal state:

override func viewDidAppear(animated: Bool) {
    moodSelector.setTitleTextAttributes(moodSelector.titleTextAttributesForState(.Normal), forState: .Selected)
}

However, this does not seem to work. Any help would be appreciated?

like image 869
user5739562 Avatar asked Jan 05 '16 02:01

user5739562


People also ask

What are segmented controls?

A segmented control is a linear set of two or more segments, each of which functions as a button. Within a segmented control, all segments are usually equal in width. Like buttons, segments can contain text or images. Segments can also have text labels beneath them (or beneath the control as a whole).

How do I create a segmented control in SwiftUI?

Since segmented control is just another variation of a picker, SwiftUI treats it as such. To create a segmented control, we create a picker view and apply a SegmentedPickerStyle() to it via the pickerStyle modifier. <1> Apply segmented picker style with . pickerStyle modifier.


1 Answers

You can set NSAttributedStringKey.foregroundColor (formerly known as NSForegroundColorAttributeName) to any color and it prevents that behavior. For example, in Swift 3 or 4:

override func viewDidLoad() {
    super.viewDidLoad()         // whether `viewDidLoad` or `viewDidAppear`, make sure to call the appropriate `super` method, too

    let attributes = [NSAttributedStringKey.foregroundColor : UIColor.white]
    moodSelector.setTitleTextAttributes(attributes, for: .selected)
}

Yielding:

segmented control with emojis

like image 74
Rob Avatar answered Oct 13 '22 01:10

Rob