Skip to content

Commit

Permalink
提供iOS功能
Browse files Browse the repository at this point in the history
  • Loading branch information
xuhom committed Jul 6, 2018
1 parent d2de993 commit 3584816
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 13 deletions.
36 changes: 24 additions & 12 deletions ios/RNMeasureText.m
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ - (dispatch_queue_t)methodQueue
reject(@"invalid_width", @"missing required width property", nil);
return;
}
if ([options objectForKey:@"texts"] == nil) {
reject(@"invalid_texts", @"missing required texts property", nil);
if ([options objectForKey:@"text"] == nil) {
reject(@"invalid_text", @"missing required text property", nil);
return;
}
if ([options objectForKey:@"fontSize"] == nil) {
Expand All @@ -35,29 +35,41 @@ - (dispatch_queue_t)methodQueue
}

float width = [RCTConvert float:options[@"width"]];
NSArray *texts = [RCTConvert NSArray:options[@"texts"]];
NSString *text = [RCTConvert NSString:options[@"text"]];
CGFloat fontSize = [RCTConvert CGFloat:options[@"fontSize"]];

NSMutableArray* results = [[NSMutableArray alloc] init];
NSMutableDictionary* result = [[NSMutableDictionary alloc] init];

UIFont *font = [UIFont systemFontOfSize: fontSize];

for (NSString* text in texts) {
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:text];

CGFloat firstHeight = 0;

for (NSString *s in [NSArray arrayWithObjects:@" ", text, nil]) {
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:s];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize: CGSizeMake(width, FLT_MAX)];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];

[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];

[textStorage addAttribute:NSFontAttributeName value:font
range:NSMakeRange(0, [textStorage length])];
[textContainer setLineFragmentPadding:0.0];
(void) [layoutManager glyphRangeForTextContainer:textContainer];
CGRect resultRect = [layoutManager usedRectForTextContainer:textContainer];

[results addObject:[NSNumber numberWithFloat:resultRect.size.height]];
if (firstHeight == 0) {
firstHeight = resultRect.size.height;
} else {
CGFloat height = resultRect.size.height;
int lines = height / firstHeight;
result[@"width"] = @(resultRect.size.width);
result[@"height"] = @(height);
result[@"lineCount"] = @(lines);
result[@"lastLineWidth"] = @(0);
}
}
resolve(results);

resolve(result);
}

@end
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-native-text-size",
"version": "1.0.0-beta.4",
"version": "1.0.0",
"description": "Measure text height and width without laying it out.",
"main": "index.js",
"types": "./index.d.ts",
Expand Down

0 comments on commit 3584816

Please sign in to comment.