HiveBrain v1.2.0
Get Started
← Back to all entries
patternswiftMinor

Set a font for a UITextView if the font is nil or not equal to desired font

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theuitextviewequaldesirednilforfontnotset

Problem

Main question

I am setting a font for a UITextView that is a subview in a custom view. I only set it if the user didn't specify the font size in the Interface Builder.

I have the following working code

if self.view.font == nil || self.view.font!.fontName != mongolFontName {
    
        view.font = UIFont(name: mongolFontName, size: defaultFontSize)
    
}


but the if line seems more verbose than it needs to be. Is there a more concise way of getting the same result?
Extra background info

This is a continuation in the same vane of a previous question. After making changes based on advice from the answers there (though still more to do), the code I have now is

```
import UIKit

@IBDesignable class UIMongolTextView: UIView {

// ** Unique to TextView **
private let view = UITextView()
let mongolFontName = "ChimeeWhiteMirrored"
let defaultFontSize: CGFloat = 17

@IBInspectable var text: String {
get {
return view.text
}
set {
view.text = newValue
}
}

@IBInspectable var fontSize: CGFloat {
get {
if let font = view.font {
return font.pointSize
} else {
return 0.0
}
}
set {
view.font = UIFont(name: mongolFontName, size: newValue)
}
}

func setup() {

view.backgroundColor = UIColor.clearColor()

// set font if user didn't specify size in IB
if self.view.font == nil || self.view.font!.fontName != mongolFontName {

view.font = UIFont(name: mongolFontName, size: defaultFontSize)
}

}




// ***
// General code for Mongol views
// ***

private var oldWidth: CGFloat = 0
private var oldHeight: CGFloat = 0

// This method ge

Solution

There's a much easier way of doing this.

if self.view.font?.fontName != mongolFontName {
    view.font = UIFont(name: mongolFontName, size: defaultFontSize)
}


We should always prefer optional binding and optional unwrapping (?) to forced (!).

When the value we're optionally unwrapping is nil, we just get nil back. And of course, nil and mongolFontName aren't going to be the same (unless you've set up mongolFontName as nil), so we enter the if's body.

Consider this example from the playground:

Code Snippets

if self.view.font?.fontName != mongolFontName {
    view.font = UIFont(name: mongolFontName, size: defaultFontSize)
}

Context

StackExchange Code Review Q#100546, answer score: 4

Revisions (0)

No revisions yet.