简易跑马灯效果,代码简单易懂,适合初学者
/** 新建文件,继承于UIView .h文件代码如下*/
#import
@interfaceTTMarqueeView :UIView
/**
* 跑马灯内容
*/
@property (nonatomic, strong) NSString *marqueeText;
/**
* 关闭定时器
*/
- (void)closeTimer;
@end
/** .m实现文件 */
#import "TTMarqueeView.h"
#import "UIView+add.h"
#define kMarqueeLeftPadding 40
// 屏幕高度
#define kScreenH [UIScreen mainScreen].bounds.size.height
// 屏幕宽度
#define kScreenW [UIScreen mainScreen].bounds.size.width
@interface TTMarqueeView ()
{
UILabel *_marqueeL;
NSTimer *_timer;
}
@end
@implementation TTMarqueeView
- (instancetype)initWithFrame:(CGRect)frame
{
if(self== [superinitWithFrame:frame]) {
[selfsetupviews];
}
return self;
}
- (void)setupviews
{
self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
UIImageView *speakerImg = [UIImageView new];
speakerImg.image= [UIImageimageNamed:@"home_speaker"];
CGSizesize = speakerImg.image.size;
speakerImg.frame=CGRectMake(10, (self.frame.size.height- size.height) /2, size.width, size.height);
[selfaddSubview:speakerImg];
UIView*marqueeBgView = [UIViewnew];
marqueeBgView.backgroundColor = [UIColor clearColor];
marqueeBgView.frame = CGRectMake(CGRectGetMaxX(speakerImg.frame) + 10, 0, self.frame.size.width - CGRectGetMaxX(speakerImg.frame), self.frame.size.height);
marqueeBgView.clipsToBounds=YES;
[selfaddSubview:marqueeBgView];
_marqueeL = ({
UILabel*label = [UILabelnew];
label.text=@"广播";
label.textColor = [UIColor whiteColor];
label.font = [UIFont systemFontOfSize:13];
label.frame=CGRectMake(0,0, marqueeBgView.frame.size.width, marqueeBgView.frame.size.height);
[marqueeBgViewaddSubview:label];
label;
});
}
- (void)closeTimer
{
if(_timer) {
[_timerinvalidate];
_timer=nil;
}
}
- (void)setMarqueeText:(NSString*)marqueeText
{
_marqueeText= marqueeText;
_marqueeL.text= marqueeText;
[_marqueeL sizeToFit];
[self closeTimer];
_marqueeL.left = kScreenW - kMarqueeLeftPadding - 10;
_marqueeL.centerY = self.height / 2;
_timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(resetMarqueeFrame) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
- (void)resetMarqueeFrame
{
_marqueeL.left = _marqueeL.left - 0.2;
if (_marqueeL.right < 0) {
_marqueeL.left = kScreenW - kMarqueeLeftPadding - 10;
}
}
@end
Demo地址:https://github.com/UsernameHwb/TTMarquee/tree/master
PS:适用初学者,希望能帮助到需要的人,如有不对,欢迎指点!