Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAttributedString combination of 2 Strings with new line

I'm trying to achieve this kind of date Date

inside a collection view cell. So i have the day's number and the month on 2 separate strings.

var day = example.date
var month = example.month

and with the functions below I'm changing them font color etc.

 func formatMonth(fullString: String, fontSize: Double) -> NSMutableAttributedString
{
    let range = (fullString as NSString).range(of: fullString)

    var myMutableString = NSMutableAttributedString()

    myMutableString = NSMutableAttributedString(string: fullString)

    myMutableString.setAttributes([NSFontAttributeName : UIFont(name: "HelveticaNeue-Bold", size: CGFloat(fontSize))!
        , NSForegroundColorAttributeName : UIColor.red], range: range)


    return myMutableString
}
func formatDay(fullString: String, fontSize: Double) -> NSMutableAttributedString
{
    let range = (fullString as NSString).range(of: fullString)

    var myMutableString = NSMutableAttributedString()

    myMutableString = NSMutableAttributedString(string: fullString)

    myMutableString.setAttributes([NSFontAttributeName : UIFont(name: "HelveticaNeue", size: CGFloat(fontSize))!
        , NSForegroundColorAttributeName : UIColor.black], range: range)


    return myMutableString
}

And the variables are becoming like this

let theMonth = formatMonth(fullString: example.month, fontSize: 15)
let theDay = formatDay(fullString: example.date, fontSize: 13)

Then i combine them

let combination = NSMutableAttributedString()
        combination.append(theDay)
        combination.append(theMonth)

and finally i get the combination of the text.

date.attributedText = combination

So by this approach i can see the one next to the other 8FEb

how can i add a breaking line between them?

like image 458
Konstantinos Natsios Avatar asked Feb 08 '17 12:02

Konstantinos Natsios


1 Answers

You can add \n with day.

let theDay = formatDay(fullString: "\(example.date)\n", fontSize: 13)

You need to set NSMutableParagraphStyle to make your text center. Try like this SO answer for that, you need to make little bit changes to make it working with Swift 3 and make sure you have sufficient height to show 2 lines.

like image 115
Nirav D Avatar answered Nov 15 '22 10:11

Nirav D