Jagdeep Singh
Jagdeep Singh

Reputation: 2626

Add option for custom font size in iOS app

I am developing an app in this app there are many text files. User clicks on a button and a files is loaded on new screen.

This file contains only text but few lines with font size 15 and other lines with font size 10. User can change font size from settings for that file.

What is right way to load the file so user increase or decrease font size?

I think attributed text is not right choice for this.

Upvotes: 0

Views: 378

Answers (1)

AamirR
AamirR

Reputation: 12198

In this use-case NSAttributedString is my best friend, and I would go with him.

Having said that, you do not have to keep large text in code files, keep the files

  1. In app bundle, you can load file from App Bundle using

    if let path = Bundle.main.path(forResource: "file1", ofType: "txt"), let text = try? String(contentsOfFile: path) {
        ...
    }
    
  2. In a remote location, you can load String from remote URL using

    if let url = URL(string: "https://www.example.org"), let text = try? String(contentsOf: url) {
        ...
    }
    

Add option for custom font size

You can add HTML tags in your text and use CSS styles, here is an example

let headerFont = UIFont(name: "ArialRoundedMTBold", size: 30)!
let headerStyle = ".heading{font-family:\(headerFont.fontName);font-size:\(Int(headerFont.pointSize));color:#000}"

let commonFont = UIFont(name: "ArialMT", size: 22)!
let commonStyle = "*{font-family:\(commonFont.fontName);font-size:\(Int(commonFont.pointSize));color:#666}"

let htmlData = Data("<style>\(commonStyle)\(headerStyle)</style>\(text)".utf8)
let attributedString = try? NSAttributedString(data: htmlData, options: [
    .documentType: NSAttributedString.DocumentType.html,
    .characterEncoding: String.Encoding.utf8.rawValue
], documentAttributes: nil)

Upvotes: 1

Related Questions