2

I am trying to show 2 strings of text in each segmented index instead of one long text. Currently the view looks like thisenter image description here

I want another string below "Repeat task" and "One time task" as marked by the red line in the image. Currently my model is

class SegmentedControlItems:NSObject{
    let title: String
    let subtitle: String

    init(title:String, subtitle:String) {
        self.title = title
        self.subtitle = subtitle
    }
}

And the code in my table view header is

        let items:[SegmentedControlItems] = {
            let item1 = SegmentedControlItems(title: "Repeat task", subtitle: "2 left")
            let item2 = SegmentedControlItems(title: "One time task", subtitle: "3 left")
            return [item1, item2]
        }()

        let segmentedControl: UISegmentedControl = {

            let segmentedControl = UISegmentedControl(items: items.map({
                $0.title
            }))
            segmentedControl.tintColor = UIColor(red:0.44, green:0.75, blue:0.27, alpha:1.0)
            segmentedControl.selectedSegmentIndex = 0
            segmentedControl.translatesAutoresizingMaskIntoConstraints = false
            return segmentedControl
        }()
        headerView.addSubview(segmentedControl)

I am creating all the views programmatically in swift4. Can anyone please help?

1 Answer 1

3

Found something like this with Objective C here

For iOS 11 and Swift 4:

For multiline, try this. It may help you.

UILabel.appearance(whenContainedInInstancesOf: [UISegmentedControl.self]).numberOfLines = 0

for i in 0..<items.count {

     var str = items[i].title
     if items[i].subtitle != "" {
       str += "\n\(items[i].subtitle)"
     }

     let myMutableString = NSMutableAttributedString(string: str, attributes: [:])
     myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:items[i].title.characters.count + 1, length:items[i].subtitle.characters.count))
     myLabel[i].attributedText = myMutableString
     mySegment.setTitle(myMutableString.string, forSegmentAt: i)
}

Output look like this (In UILabel its working, but not in UISegmentControl) Hope someone will do that:

In UILabel its work but not in UISegmentControl

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.