Forked from m-abs/label-max-lines.directive.ts
Last active
November 22, 2023 06:13
-
-
Save EddyVerbruggen/8232252e3a4667e7e20916279f98d3fc to your computer and use it in GitHub Desktop.
Directive for NativeScript-angular, adding the property maxLines to Label
This file contains 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
// Usage: <Label maxLines="3" .. /> | |
import { Directive, ElementRef, Input, OnInit, OnChanges } from '@angular/core'; | |
import { Label } from 'tns-core-modules/ui/label'; | |
declare const android, NSLineBreakMode: any; | |
@Directive({ | |
selector: 'Label[maxLines]', | |
}) | |
export class LabelMaxLinesDirective implements OnInit, OnChanges { | |
@Input('maxLines') public maxLines: number = 1; | |
public get nativeView(): Label { | |
return this.el.nativeElement; | |
} | |
constructor(private el: ElementRef) {} | |
public ngOnInit() { | |
const nativeView = this.nativeView; | |
if (nativeView instanceof Label) { | |
nativeView.on(Label.loadedEvent, () => { | |
this.applyMaxLines(); | |
}); | |
} | |
} | |
public ngOnChanges(changes: any) { | |
if (changes.maxLines) { | |
this.applyMaxLines(); | |
} | |
} | |
private applyMaxLines() { | |
const nativeView = this.nativeView; | |
const maxLines = Math.max(Number(this.maxLines) || 0, 1); | |
if (nativeView.android) { | |
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
@huuthangdut or @mrcretu can show a code example for the sizeToFit() function please'
I tried but the label didn't change.
Thanks!
Marco