This commit is contained in:
2025-11-11 19:39:33 +08:00
parent 20b13bcffa
commit 3440cc4773
4 changed files with 349 additions and 0 deletions

View File

@@ -0,0 +1,264 @@
//
// KBStreamTextView.m
// KeyBoard
//
//
// "\t" UILabel
// UIScrollView
//
#import "KBStreamTextView.h"
@interface KBStreamTextView ()
//
@property (nonatomic, strong) UIScrollView *scrollView;
//
@property (nonatomic, strong) NSMutableArray<UILabel *> *labels;
//
@property (nonatomic, copy) NSString *buffer;
@end
@implementation KBStreamTextView
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self commonInit];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder {
if (self = [super initWithCoder:coder]) {
[self commonInit];
}
return self;
}
- (void)commonInit {
_delimiter = @"\t";
_labelFont = [UIFont systemFontOfSize:16.0];
if (@available(iOS 13.0, *)) {
_labelTextColor = [UIColor labelColor];
} else {
_labelTextColor = [UIColor blackColor];
}
_contentHorizontalPadding = 12.0;
_interItemSpacing = 5.0; // 5pt
_labels = [NSMutableArray array];
_buffer = @"";
_shouldTrimSegments = YES;
//
_scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
_scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
_scrollView.alwaysBounceVertical = YES;
_scrollView.showsVerticalScrollIndicator = YES;
[self addSubview:_scrollView];
}
#pragma mark - Public API
// label label
- (void)appendStreamText:(NSString *)text {
if (text.length == 0) { return; }
// 线线 UI
if (![NSThread isMainThread]) {
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf appendStreamText:text];
});
return;
}
// 退
if (self.delimiter.length == 0) {
[self ensureCurrentLabelExists];
self.buffer = [self.buffer stringByAppendingString:text];
self.labels.lastObject.text = self.buffer;
[self layoutLabelsForCurrentWidth];
[self scrollToBottomIfNeeded];
return;
}
// label
[self ensureCurrentLabelExists];
// parts.count = = parts.count - 1
NSArray<NSString *> *parts = [text componentsSeparatedByString:self.delimiter];
// 1)
self.buffer = [self.buffer stringByAppendingString:parts.firstObject ?: @""];
self.labels.lastObject.text = self.buffer; //
[self layoutLabelsForCurrentWidth];
// 2)
for (NSUInteger i = 1; i < parts.count; i++) {
// a)
UILabel *current = self.labels.lastObject;
if (self.shouldTrimSegments) {
NSString *trimmed = [current.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
current.text = trimmed;
}
[self layoutLabelsForCurrentWidth];
// b)
[self createEmptyLabelAsNewSegment];
// c)
NSString *piece = parts[i];
self.buffer = piece ?: @"";
self.labels.lastObject.text = self.buffer;
[self layoutLabelsForCurrentWidth];
}
[self scrollToBottomIfNeeded];
}
- (void)reset {
for (UILabel *lbl in self.labels) {
[lbl removeFromSuperview];
}
[self.labels removeAllObjects];
self.buffer = @"";
self.scrollView.contentSize = CGSizeMake(self.bounds.size.width, 0);
}
#pragma mark - Layout Helpers
- (void)addLabelForText:(NSString *)text {
if (self.shouldTrimSegments) {
text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
// UILabel
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.numberOfLines = 0;
label.font = self.labelFont;
label.textColor = self.labelTextColor;
label.userInteractionEnabled = YES; //
label.text = text;
//
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleLabelTap:)];
[label addGestureRecognizer:tap];
[self.scrollView addSubview:label];
[self.labels addObject:label];
//
[self layoutLabelsForCurrentWidth];
//
[self scrollToBottomIfNeeded];
}
#pragma mark - Streaming Helpers
// label
- (void)ensureCurrentLabelExists {
if (self.labels.lastObject) { return; }
[self createEmptyLabelAsNewSegment];
}
//
- (void)createEmptyLabelAsNewSegment {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.numberOfLines = 0;
label.font = self.labelFont;
label.textColor = self.labelTextColor;
label.userInteractionEnabled = YES;
label.text = @"";
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleLabelTap:)];
[label addGestureRecognizer:tap];
[self.scrollView addSubview:label];
[self.labels addObject:label];
self.buffer = @"";
[self layoutLabelsForCurrentWidth];
}
- (void)finishStreaming {
if (![NSThread isMainThread]) {
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf finishStreaming];
});
return;
}
UILabel *current = self.labels.lastObject;
if (!current) { return; }
if (self.shouldTrimSegments) {
NSString *trimmed = [current.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
current.text = trimmed;
self.buffer = trimmed;
[self layoutLabelsForCurrentWidth];
}
}
- (void)layoutSubviews {
[super layoutSubviews];
// /
[self layoutLabelsForCurrentWidth];
}
- (void)layoutLabelsForCurrentWidth {
CGFloat width = self.bounds.size.width;
if (width <= 0) { return; }
CGFloat x = self.contentHorizontalPadding;
CGFloat maxLabelWidth = MAX(0.0, width - 2.0 * self.contentHorizontalPadding);
CGFloat y = self.interItemSpacing; //
for (NSUInteger idx = 0; idx < self.labels.count; idx++) {
UILabel *label = self.labels[idx];
CGSize size = [self sizeForText:label.text font:label.font maxWidth:maxLabelWidth];
label.frame = CGRectMake(x, y, maxLabelWidth, size.height);
y += size.height;
// 5pt
if (idx + 1 < self.labels.count) {
y += self.interItemSpacing;
}
}
CGFloat contentHeight = MAX(y + self.interItemSpacing, self.bounds.size.height + 1.0);
self.scrollView.contentSize = CGSizeMake(width, contentHeight);
}
- (CGSize)sizeForText:(NSString *)text font:(UIFont *)font maxWidth:(CGFloat)maxWidth {
if (text.length == 0) {
//
return CGSizeMake(maxWidth, font.lineHeight);
}
CGRect rect = [text boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:@{NSFontAttributeName: font}
context:nil];
//
return CGSizeMake(maxWidth, ceil(rect.size.height));
}
- (void)scrollToBottomIfNeeded {
CGFloat height = self.scrollView.bounds.size.height;
CGFloat contentHeight = self.scrollView.contentSize.height;
if (contentHeight > height && height > 0) {
CGPoint bottomOffset = CGPointMake(0, contentHeight - height);
[self.scrollView setContentOffset:bottomOffset animated:YES];
}
}
#pragma mark - Tap Handling
- (void)handleLabelTap:(UITapGestureRecognizer *)tap {
UILabel *label = (UILabel *)tap.view;
if (![label isKindOfClass:[UILabel class]]) { return; }
NSInteger index = [self.labels indexOfObject:label];
if (index != NSNotFound && self.onLabelTap) {
self.onLabelTap(index, label.text ?: @"");
}
}
@end