As you my have experienced or seen me angrily tweet about, WKInterfaceLabels
in WatchKit
have a finite length. The length seems to hover around the 7657 characters, which sure, while that is longer than the average Wikipedia article, it’s still a weird bug.
So, what can you do aside from filing a bug report that would surely be closed a duplicate since I already beat you to it?
Well, you can workaround it, isn’t WatchKit fun!
Why does the bug actually occur?
I dunno
How can I fix it?
Unlike UIKit
, a WKInterfaceLabel
is the only way to present text in WatchKit
. But in order to fix it you have to break down your text into multiple labels. In order to do this, I use a WKInterfaceTable
with a row controller which only contains a single WKInterfaceLabel
.
Now, you need a function to break up your text into smaller chunks before you can put it into a table. I created a function for this which takes an input String
, as well as a wordCount
parameter, indicating the max size for each chunk.
func split(text: String, wordCount count: Int) -> [String]{
var splitContents = text.split(separator: " ")
var seperatedContents = [String]()
for _ in 0 ... splitContents.count / count{
seperatedContents.append(splitContents.prefix(count).joined(separator: " "))
splitContents = Array(splitContents.dropFirst(count))
}
return seperatedContents
}
Let’s break this down:
var splitContents = text.split(separator: " ")
This is splitting the text up into an array of words, or just wherever a space is.
"This is splitting the text up" -> ["This", "is", "splitting", "the", "text", "up"]
var seperatedContents = [String]()
This just creates an array to hold our chunks.
for _ in 0 ... splitContents.count / count{
This creates a for
loop, which will run just enough times. First, the number of words is counted, this is done by counting each word in the input text, and dividing that by the desired word count. So for an input text with 200 words and a 100 word chunk size, this will run twice.
seperatedContents.append(splitContents.prefix(count).joined(separator: " "))
What this does is take the first count
(the word count specified) elements of the split contents and join them back together, and append that to array of chunks we created before (separatedContents
).
splitContents = Array(splitContents.dropFirst(count))
This just removes the elements we’ve already processed so we don’t get duplicates.
return seperatedContents
You all know what this does 🙂
Now what?
Now take your returned contents and fill your WKInterfaceTable
with them. I won’t go into how to do that here, but I have a tutorial which does explain how to do that (as well as explaining some other stuff)
The End
I hope you found this post useful, and I hope Apple fixes this weird bug in watchOS 6!