您可以通过测量文本的长度并调用大小以适合标签来实现所需的效果。然后将标签的框架(或周围的 superView,如果需要)偏移到屏幕的左侧或右侧。
这是一个快速的方法(最好在别处声明变量 maxWidth 和 padding)。请注意,“w”是屏幕宽度的变量。
-(UIView *)bubbleWithText:(NSString *)text atOffset:(float)yOff isLeftAligned:(bool)leftAligned {
float maxWidth = 200.0f;
float intraCellPadding = 5.0f;
UILabel * label = [UILabel new];
label.frame = CGRectMake(intraCellPadding, intraCellPadding, maxWidth, 0);
label.textColor = (leftAligned) ? [UIColor blackColor] : [UIColor whiteColor];
label.text = text;
label.numberOfLines = 0;
[label sizeToFit];
float width = label.frame.size.width;
float height = label.frame.size.height;
float xOff = (leftAligned) ? intraCellPadding : w-3*intraCellPadding-width;
UIView * bubble = [UIView new];
bubble.frame = CGRectMake(xOff, yOff, width + 2 * intraCellPadding, height + 2 * intraCellPadding);
bubble.backgroundColor = (leftAligned) ? [UIColor greenColor] : [UIColor blueColor];
bubble.layer.cornerRadius = intraCellPadding;
[bubble addSubview:label];
return bubble;
}
你会用这样的方式调用上面的代码:
float interCellPadding = 10.0f;
float yOff = 20.0f;
bool previousWasLeft = false;
NSArray * texts = @[@"Bacon ipsum dolor amet kevin swine ham hock, leberkas porchetta salami bacon picanha shoulder pig strip steak sirloin.",
@"Short loin hamburger meatloaf jowl, sirloin swine pork belly tail t-bone venison.",
@"Flank meatloaf prosciutto ball tip strip steak rump.",
@"Short piggy.",
@"Tri-tip ribeye drumstick andouille leberkas bacon pork chop meatball pork spare ribs chicken.",
@"Strip steak filet mignon tri-tip sausage, cow frankfurter bacon ribeye cupim burgdoggen shank pork belly fatback ham hock."];
for (NSString * text in texts){
//random assignment left / right
//by creating a random number, either one or zero
//this doubles up as a boolean
bool alignLeft = arc4random_uniform(2);
//here we increment the offset
//depending on whether the previous bubble
//was on the same side or not, giving a
//bit more space for alternating bubbles.
yOff += (previousWasLeft != alignLeft) ? interCellPadding : interCellPadding/2.0f;
previousWasLeft = alignLeft;
//create the bubble and add
UIView * bubble = [self bubbleWithText:text atOffset:yOff isLeftAligned:alignLeft];
[self.view addSubview:bubble]; //or scrollView whatever
//incrmeent the offset
yOff += bubble.frame.size.height;
}
这是快速而肮脏的,但显示了如何实现您所需要的。对于很多单元格(这可能是您想要的),如果您要使用自定义路线,则必须注意从内存中释放它们。调整 UICollectionView 单元格并简单地对齐其中的内容可能会更容易。