Skip to content

Commit

Permalink
Adds TabWidthMeasurer (#360)
Browse files Browse the repository at this point in the history
* Adds TabWidthMeasurer

* Fixes typo
  • Loading branch information
simonbs authored Mar 16, 2024
1 parent 392e97f commit e21d5ac
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 7 deletions.
12 changes: 12 additions & 0 deletions Sources/Runestone/Library/TabWidthMeasurer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import UIKit

enum TabWidthMeasurer {
static func tabWidth(tabLength: Int, font: UIFont) -> CGFloat {
let str = String(repeating: " ", count: tabLength)
let maxSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: .greatestFiniteMagnitude)
let options: NSStringDrawingOptions = [.usesFontLeading, .usesLineFragmentOrigin]
let attributes: [NSAttributedString.Key: Any] = [.font: font]
let bounds = str.boundingRect(with: maxSize, options: options, attributes: attributes, context: nil)
return round(bounds.size.width)
}
}
7 changes: 1 addition & 6 deletions Sources/Runestone/TextView/Indent/IndentController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,7 @@ final class IndentController {
if let tabWidth = _tabWidth {
return tabWidth
} else {
let str = String(repeating: " ", count: indentStrategy.tabLength)
let maxSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: .greatestFiniteMagnitude)
let options: NSStringDrawingOptions = [.usesFontLeading, .usesLineFragmentOrigin]
let attributes: [NSAttributedString.Key: Any] = [.font: indentFont]
let bounds = str.boundingRect(with: maxSize, options: options, attributes: attributes, context: nil)
let tabWidth = round(bounds.size.width)
let tabWidth = TabWidthMeasurer.tabWidth(tabLength: indentStrategy.tabLength, font: indentFont)
if tabWidth != _tabWidth {
_tabWidth = tabWidth
delegate?.indentControllerDidUpdateTabWidth(self)
Expand Down
2 changes: 1 addition & 1 deletion Sources/Runestone/TextView/Indent/IndentStrategy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Foundation

/// Strategy to use when indenting text.
public enum IndentStrategy: Equatable {
/// Indent using tabs. The length specified length is used to determine the width of the tab measured in space characers.
/// Indent using tabs. The specified length is used to determine the width of the tab measured in space characers.
case tab(length: Int)
/// Indent using a number of spaces.
case space(length: Int)
Expand Down

0 comments on commit e21d5ac

Please sign in to comment.