回答編集履歴
2
追記
answer
CHANGED
@@ -19,4 +19,46 @@
|
|
19
19
|
print(countLines("あああ")) // 1
|
20
20
|
print(countLines("あああ\nいいい")) // 2
|
21
21
|
print(countLines("あああ\nいいい\n")) // 3
|
22
|
-
```
|
22
|
+
```
|
23
|
+
|
24
|
+
-------------
|
25
|
+
|
26
|
+
### 2019/05/27 追記
|
27
|
+
|
28
|
+
自動改行も含むということで、UITextViewのクローンを生成し(フォントサイズなどを引き継げればなんでもいいです)、新しいテキストを流し込み、表示されている行数を調べるという手法で実装してみました。
|
29
|
+
|
30
|
+
```swift
|
31
|
+
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
|
32
|
+
|
33
|
+
let newText: String = (textView.text! as NSString).replacingCharacters(in: range, with: text)
|
34
|
+
return numberOfLines(orgTextView: textView, newText: newText) <= 3
|
35
|
+
}
|
36
|
+
|
37
|
+
private func numberOfLines(orgTextView: UITextView, newText: String) -> Int {
|
38
|
+
|
39
|
+
// UITextViewを複製します。iOS12では古いAPIを使っているというような警告がでます。
|
40
|
+
let cloneTextView = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: orgTextView)) as! UITextView
|
41
|
+
|
42
|
+
cloneTextView.text = newText + " "
|
43
|
+
|
44
|
+
let layoutManager = cloneTextView.layoutManager
|
45
|
+
let numberOfGlyphs = layoutManager.numberOfGlyphs
|
46
|
+
var numberOfLines = 0
|
47
|
+
var index = 0
|
48
|
+
var lineRange = NSRange()
|
49
|
+
|
50
|
+
while index < numberOfGlyphs {
|
51
|
+
layoutManager.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange)
|
52
|
+
index = NSMaxRange(lineRange);
|
53
|
+
numberOfLines = numberOfLines + 1
|
54
|
+
}
|
55
|
+
|
56
|
+
return numberOfLines
|
57
|
+
}
|
58
|
+
```
|
59
|
+
|
60
|
+
ろくに動作チェックはしていませんが、それとなく動いたところまでは確認しました。
|
61
|
+
|
62
|
+
参考資料:
|
63
|
+
[Counting the number of lines in a UITextView, lines wrapped by frame size
|
64
|
+
](https://stackoverflow.com/questions/5837348/counting-the-number-of-lines-in-a-uitextview-lines-wrapped-by-frame-size)
|
1
ちょっと修正
answer
CHANGED
@@ -5,6 +5,7 @@
|
|
5
5
|
|
6
6
|
```swift
|
7
7
|
func countLines(_ string: String) -> Int {
|
8
|
+
let string = string + " "
|
8
9
|
var count = 0
|
9
10
|
string.enumerateLines { _, _ in
|
10
11
|
count += 1
|
@@ -14,7 +15,8 @@
|
|
14
15
|
```
|
15
16
|
|
16
17
|
```text
|
17
|
-
print(countLines("")) //
|
18
|
+
print(countLines("")) // 1
|
18
19
|
print(countLines("あああ")) // 1
|
19
20
|
print(countLines("あああ\nいいい")) // 2
|
21
|
+
print(countLines("あああ\nいいい\n")) // 3
|
20
22
|
```
|