Skip to content

Commit e21d5ac

Browse files
authored
Adds TabWidthMeasurer (#360)
* Adds TabWidthMeasurer * Fixes typo
1 parent 392e97f commit e21d5ac

3 files changed

Lines changed: 14 additions & 7 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import UIKit
2+
3+
enum TabWidthMeasurer {
4+
static func tabWidth(tabLength: Int, font: UIFont) -> CGFloat {
5+
let str = String(repeating: " ", count: tabLength)
6+
let maxSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: .greatestFiniteMagnitude)
7+
let options: NSStringDrawingOptions = [.usesFontLeading, .usesLineFragmentOrigin]
8+
let attributes: [NSAttributedString.Key: Any] = [.font: font]
9+
let bounds = str.boundingRect(with: maxSize, options: options, attributes: attributes, context: nil)
10+
return round(bounds.size.width)
11+
}
12+
}

Sources/Runestone/TextView/Indent/IndentController.swift

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,7 @@ final class IndentController {
3030
if let tabWidth = _tabWidth {
3131
return tabWidth
3232
} else {
33-
let str = String(repeating: " ", count: indentStrategy.tabLength)
34-
let maxSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: .greatestFiniteMagnitude)
35-
let options: NSStringDrawingOptions = [.usesFontLeading, .usesLineFragmentOrigin]
36-
let attributes: [NSAttributedString.Key: Any] = [.font: indentFont]
37-
let bounds = str.boundingRect(with: maxSize, options: options, attributes: attributes, context: nil)
38-
let tabWidth = round(bounds.size.width)
33+
let tabWidth = TabWidthMeasurer.tabWidth(tabLength: indentStrategy.tabLength, font: indentFont)
3934
if tabWidth != _tabWidth {
4035
_tabWidth = tabWidth
4136
delegate?.indentControllerDidUpdateTabWidth(self)

Sources/Runestone/TextView/Indent/IndentStrategy.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import Foundation
22

33
/// Strategy to use when indenting text.
44
public enum IndentStrategy: Equatable {
5-
/// Indent using tabs. The length specified length is used to determine the width of the tab measured in space characers.
5+
/// Indent using tabs. The specified length is used to determine the width of the tab measured in space characers.
66
case tab(length: Int)
77
/// Indent using a number of spaces.
88
case space(length: Int)

0 commit comments

Comments
 (0)