Count the number of lines in a Swift String
If it's ok for you to use a Foundation method on an NSString, I suggest using
enumerateLines(_ block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void)
Here's an example:
import Foundation
let base = "Hello, playground\r\nhere too\r\nGalahad\r\n"
let ns = base as NSString
ns.enumerateLines { (str, _) in
print(str)
}
It separates the lines properly, taking into account all linefeed types, such as "\r\n", "\n", etc:
Hello, playground
here too
Galahad
In my example I print the lines but it's trivial to count them instead, as you need to - my version is just for the demonstration.
Counting lines in Swift
This is the solution to the problem I found so I will leave it here in case someone else finds it useful.
var text = "Line 1\nLine 2\nLine 3"
for var range = text.startIndex...text.startIndex; range.endIndex < text.endIndex;
range = range.endIndex..<range.endIndex {
range = text.lineRangeForRange(range)
}
Count lines in the file Swift
Try changing the terminator to "\n".
It is possible your file has Unix-like line endings. Meaning lines will be terminated with \n.
Unix-like systems (such as OS X and iOS) typically terminate lines with \n.
Windows terminates lines with \r\n.
Source: https://en.wikipedia.org/wiki/Newline#Representations
Count number of lines in a txt/log -file, swift
I can't help you with swift but the logic would assume you proceed like this :
(which seems very close to what you did)
- Get your file in a
string
. You've done that. - Separate that
string
in anarray
(with a redundant character that would mark the end of the line in your document or an newline character (\n) ) You've done that. - simply
count
the items in thearray
(You're using a string in a way that eludes me because i can't really read swift)
I'm guessing
var myCount = textArr.count
That would give you an int
which you can do whatever you want with.
Note though that if you want to access that line in the array you'll have to use n-1
because, as you most certainly know, if your count is 1, the item is at index count-1
so zero. which is also maybe why you're getting an out of bounds error
How to count characters excluding new lines in Swift?
You can use filter(isIncludedIn:)
to exclude something from a Sequence:
let str = "abc\ndef\nghi"
let charsNumber = str.characters.filter {$0 != "\n" && $0 != "\r"}.count
print(charsNumber) //-> 9
If the str
is very large, this may be a little more efficient:
let charsNumber = str.characters.lazy.filter {$0 != "\n" && $0 != "\r"}.count
How to find actual number of lines of UILabel?
Firstly set text in UILabel
First Option :
Firstly calculate height for text according to font :
NSInteger lineCount = 0;
CGSize labelSize = (CGSize){yourLabel.frame.size.width, MAXFLOAT};
CGRect requiredSize = [self boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: yourLabel.font} context:nil];
Now calculate number of lines :
int charSize = lroundf(yourLabel.font.lineHeight);
int rHeight = lroundf(requiredSize.height);
lineCount = rHeight/charSize;
NSLog(@"No of lines: %i",lineCount);
Second Option :
NSInteger lineCount = 0;
CGSize textSize = CGSizeMake(yourLabel.frame.size.width, MAXFLOAT);
int rHeight = lroundf([yourLabel sizeThatFits:textSize].height);
int charSize = lroundf(yourLabel.font.lineHeight);
lineCount = rHeight/charSize;
NSLog(@"No of lines: %i",lineCount);
SwiftUI Text Editor how can I keep track of the number of lines in the editor
I got it to work smoothly and I just needed to make a few changes . With the changes below I just track the size of the Text instead of the number of lines and update the TextEditor accordingly . For the number of lines it only worked when I would press enter .
struct CommentVTestView: View {
@State var Posting = ""
@State var height: CGFloat = 30.0
var body: some View {
VStack(alignment: .leading) {
TextEditor(text: $Posting)
.foregroundColor(.black)
.font(Font.custom("Helvetica Neue", size: 15))
.border(Color.gray)
.padding([.bottom], 5)
.foregroundColor(.secondary)
.cornerRadius(3)
.frame(width: 200, height: height)
Text(Posting)
.foregroundColor(.red)
.frame(width: 190)
.hidden()
.font(Font.custom("Helvetica Neue", size: 15))
.fixedSize(horizontal: false, vertical: true)
.background(GeometryReader { proxy in
Color.clear
.onChange(of: self.Posting, perform: { value in
if proxy.size.height > height {
height = proxy.size.height + 17.0
}
})
})
}
}
}
Counting the number of lines in a UITextView, lines wrapped by frame size
This variation takes into account how you wrap your lines and the max size of the UITextView
, and may output a more precise height. For example, if the text doesn't fit it will truncate to the visible size, and if you wrap whole words (which is the default) it may result in more lines than if you do otherwise.
UIFont *font = [UIFont boldSystemFontOfSize:11.0];
CGSize size = [string sizeWithFont:font
constrainedToSize:myUITextView.frame.size
lineBreakMode:UILineBreakModeWordWrap]; // default mode
float numberOfLines = size.height / font.lineHeight;
Related Topics
Get the String Up to a Specific Character
Dismiss View from View Model [Modal Page]
Swift Optionals - Why Does Var A:Int? A? = 4 Return Nil
How to Add Icon to a Share Sheet in Swift
Why Mark Something Final in Swift Except for Architectural Considerations
How to Segue Values When My Viewcontroller Is Embedded in an Uinavigationcontroller
Swift: How to Fix Infinite Loop When Adding a Value to a Firebase Variable
Differences Generic Protocol Type Parameter VS Direct Protocol Type
Swift Error: 'Sequence' Requires the Types 'T' and 'Arrayslice<T>' Be Equivalent
iOS Swift - Uitableviewcell Custom Subclass Not Displaying Content
Moving Skspritenode to Location of the Touch
Realm Swift: Always Put Nil Values Last in Sort
iOS Firebase: Firauthuidelegate.Authui Not Being Called
Why Can't I Use Subscripting on a Ckrecord Object in Swift
Saving Dictionary into Nsuserdefaults
Scrolling Delegate in Tableview