需求:有一个动态需要更新的TableView,每一个Cell显示的内容从网络获取,并且Cell中有一个需要显示文字的Label,当文字太长的时候,不能完全显示,所以采用跑马灯的样式
实现:1. IB的方式(✔️)
2.纯代码(❎)
IB的层次关系
实现的功能:
1.动态获取文字的实际长度
2.设置滚动的收尾位置
代码:
1.TitleRolling.h
@interface TitleRolling : UIViewController
-(void) startScroll : (UIScrollView*) scrollview;
@end
2.TitleRolling.m
#import "TitleRolling.h"
#pragma mark - Class define variable
#define K_MAIN_VIEW_SCROLL_HEIGHT 20.0f
#define K_MAIN_VIEW_SCROLL_TEXT_TAG 300
#define K_MAIN_VIEW_TEME_INTERVAL 0.35 //计时器间隔时间(单位秒)
#define K_MAIN_VIEW_SCROLLER_SPACE 20 //每次移动的距离
#define K_MAIN_VIEW_SCROLLER_LABLE_WIDTH 280 //字体宽度
#define K_MAIN_VIEW_SCROLLER_LABLE_MARGIN 20 //前后间隔距离
#define K_MAIN_VIEW_SCROLLER_LABLE_LENGTH2LEFT 20 //设置开头距离左侧的边距
-(void) startScroll : (UIScrollView*) view{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:view forKey:@"scrollView"];
NSTimer *timer_hsf = [NSTimer scheduledTimerWithTimeInterval:K_MAIN_VIEW_TEME_INTERVAL target:self selector:@selector(OnTimesetScrollText: ) userInfo:dict repeats:YES];
[timer_hsf fire];
}
-(void) OnTimesetScrollText:(NSTimer *)timer{
UIScrollView* view = [[timer userInfo] objectForKey:@"scrollView"];
[UIView animateWithDuration:K_MAIN_VIEW_TEME_INTERVAL * 2 animations:^{
CGRect rect;
CGFloat offsetX = 0.0;
//NSLog(@"view的子视图数量%lu",(unsigned long)view.subviews.count);
UILabel *lab = view.subviews[0];
// for (UILabel *lab in view.subviews) {
//NSLog(@"lab: %f view:%f",lab.frame.size.width,view.frame.size.width);
rect = lab.frame;
offsetX = rect.origin.x - K_MAIN_VIEW_SCROLLER_SPACE;
if (offsetX < - (rect.size.width-view.frame.size.width+4*K_MAIN_VIEW_SCROLLER_LABLE_LENGTH2LEFT))
{
offsetX = K_MAIN_VIEW_SCROLLER_LABLE_MARGIN + K_MAIN_VIEW_SCROLLER_LABLE_LENGTH2LEFT;//设置初始位置
}
lab.frame = CGRectMake(offsetX, rect.origin.y, rect.size.width, rect.size.height);
// }
//NSLog(@"offsetX:%f",offsetX);
}];
}
#pragma 文字自适应宽度,该代码只有在纯代码模式里边,设置UILabel时候会使用到
- (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1000, 0)];
label.text = title;
label.font = font;
[label sizeToFit];
return label.frame.size.width;
}
调用:
在ViewController中设置TableView的代理:
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//单元格ID
static NSString *CellTableIndentifier = @"HSFCell";
//重用单元格
HSF_liquidText *cell = [tableView dequeueReusableCellWithIdentifier:CellTableIndentifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.0f];//单元格透明step2
//添加图片
cell.CaseTextContent.text = @"南山区1234567就暗示的看见爱上大家哈山东矿机爱神的箭好看好看";
//添加右侧注释
TitleRolling *newTitle = [[TitleRolling alloc] init];
if(cell.CaseScrollView != nil)
{
//[cell.CaseScrollView addSubview:cell.CaseTextContent];
[newTitle startScroll:cell.CaseScrollView];
}
else
NSLog(@"cell的父视图:%@",cell.superview);
return cell;
}