After entering text in TextInput
I want to know the currunt number of lines in TextInput
.
Or
The current number of strings
is also possible.
I've tried string.split('\n').length
, but this code does not detect that the line is automatically incremented when the text is larger than the screen.
How do I get the number of lines
When I make this feature in Swift
Implemented using the string.enumerateLines
function.
Do you have a similar function?
As far as I know, there is no offical way to get the currently used number of lines, but I have a workaround for you:
We make use of the onLayout
method of our TextInput
and we keep track of the currently used height. We need two state variables:
this.state = {
height: 0, // here we track the currently used height
usedLines: 0,// here we calculate the currently used lines
}
onLayout:
_onLayout(e) {
console.log('e', e.nativeEvent.layout.height);
// the height increased therefore we also increase the usedLine counter
if (this.state.height < e.nativeEvent.layout.height) {
this.setState({usedLines: this.state.usedLines+1});
}
// the height decreased, we subtract a line from the line counter
if (this.state.height > e.nativeEvent.layout.height){
this.setState({usedLines: this.state.usedLines-1});
}
// update height if necessary
if (this.state.height != e.nativeEvent.layout.height){
this.setState({height: e.nativeEvent.layout.height});
}
}
Render Method
render() {
console.log('usedLines', this.state.usedLines);
return (
<View style={styles.container}>
<TextInput multiline style={{backgroundColor: 'green'}} onLayout={(e)=> this._onLayout(e)} />
</View>
);
}
Working Example: