Created
January 22, 2024 18:53
-
-
Save mukaschultze/b8ab1b690dfbeade7a012a24bb8d6870 to your computer and use it in GitHub Desktop.
Max line directive NativeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, ElementRef, Input, OnInit, OnChanges } from '@angular/core'; | |
import { Label } from '@nativescript/core'; | |
@Directive({ selector: 'Label[maxLines]' }) | |
export class LabelMaxLinesDirective implements OnInit, OnChanges { | |
constructor(private el: ElementRef) {} | |
@Input() public maxLines = 1; | |
public get nativeView(): Label { | |
return this.el.nativeElement; | |
} | |
public ngOnChanges(changes: any) { | |
if (changes.maxLines) { | |
this.applyMaxLines(); | |
} | |
} | |
public ngOnInit() { | |
const nativeView = this.nativeView; | |
if (nativeView instanceof Label) { | |
nativeView.on(Label.loadedEvent, () => { | |
this.applyMaxLines(); | |
}); | |
} | |
} | |
private applyMaxLines() { | |
const nativeView = this.nativeView; | |
const maxLines = Math.max(Number(this.maxLines) || 0, 1); | |
if (nativeView.android) { | |
nativeView.android.setSingleLine(false); | |
nativeView.android.setMaxLines(maxLines); | |
nativeView.android.setEllipsize(android.text.TextUtils.TruncateAt.END); | |
} else if (nativeView.ios) { | |
setTimeout(() => { | |
nativeView.ios.numberOfLines = maxLines; | |
nativeView.ios.adjustsFontSizeToFitWidth = false; | |
nativeView.ios.lineBreakMode = NSLineBreakMode.ByTruncatingTail; | |
}, 0); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment