IOS UILabel 如何实现随机摆放以及刷新

最近项目需要实现数据随机显示在视图上,并且点击空白重新刷新,经过探索,终于实现随机显示。。。下面开始说明!

首先介绍一下个人思路,简单来说,每一个Label上显示的文字,可以用[string sizeWithFont:]之类的函数算出size,然后随机一个origin来生成一个frame,然后依次处理每个Label,将正在处理的Label的frame和前面已设置好Label的frame进行一下判断,使用CGRectIntersectsRect来判断是否有交集,同时还要判断该Label是否超出视图View,如果有交集或超出则重新生成点

直接上代码:

- (id)initWithFrame:(CGRect)frame 
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        NSArray *bklist=@[@"CSDN",@"IOS 7.0",@"http://blog.csdn.net/lsy2013",@"www.baidu.com"];
        list=[[NSMutableArray alloc]initWithArray:bklist];
        self.backgroundColor=[UIColor whiteColor];
        [self initBkList:bklist];
        [self setUserInteractionEnabled:YES];
        UITapGestureRecognizer *tapGestureTel = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewReload)];
        [self addGestureRecognizer:tapGestureTel];
    }
    return self;
}

-(void)initBkList:(NSArray *)bklist//存放NSString数组
{
        int locatag=0;
        for (int j=0; j<bklist.count; j++)
        {
            UILabel * label = [[UILabel alloc]init];
            label.font=[UIFont systemFontOfSize:18];
             NSTimeInterval animationDuration = 0.50f;
             [UIView beginAnimations:nil context:nil];
             [UIView setAnimationDuration:animationDuration];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
            label.textAlignment=NSTextAlignmentLeft;
            label.text=bklist[j] ;
            label.frame=[self randomRect:[bklist[j] baikeTitel] AndLabelCount:j];
            //label.backgroundColor  = [UIColor redColor];
            [self addSubview:label];
             [UIView commitAnimations];       
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(CGSize)labelAuto:(NSString *)str
{
    UIFont * tfont = [UIFont systemFontOfSize:18];
    CGSize size =CGSizeMake(1024,50);
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil];
    CGSize  actualsize =[str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
    return actualsize;
}


-(CGRect)randomRect:(NSString *)str AndLabelCount:(NSInteger)count
{
    BOOL isIntersect=NO;
    int x = arc4random() % (int)self.frame.size.width;
    int y =  arc4random() % (int)self.frame.size.height;
    CGSize actualsize=[self labelAuto:str];
    CGRect labelFrame= CGRectMake(x, y, actualsize.width, actualsize.height);
    do {
        int i=0;
        if ((labelFrame.origin.x+labelFrame.size.width)>self.frame.size.width||(labelFrame.origin.y+labelFrame.size.height)>self.frame.size.height)
        {
            isIntersect=YES;
        }else
        {
        isIntersect=NO;
        for (id obj in self.subviews)
        {
            if ([obj isKindOfClass:[UILabel class]])
            {
                i++;
                UILabel * mylabel = (UILabel*)obj;
                if (CGRectIntersectsRect(labelFrame,mylabel.frame))
                {
                    isIntersect=YES;
                    break;
                }
            }
            if (i==count)
            {
                isIntersect=NO;
            }
        }
        }
        if (isIntersect)
        {
            x = arc4random() % (int)self.frame.size.width;
            y = arc4random() % (int)self.frame.size.height;
            labelFrame= CGRectMake(x, y, actualsize.width, actualsize.height);
        }
    } while (isIntersect);
    return labelFrame;
}
-(void)viewReload
{
    for (id obj in self.subviews)
    {
        if ([obj isKindOfClass:[UILabel class]])
        {
            UILabel * mylabel = (UILabel*)obj;
            [mylabel removeFromSuperview];
        }

    }
    [self initBkList:list];
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS 中的 UILabel 是一种用于显示文本的控件,它可以用于显示降价信息。你可以使用具有 Markdown 格式的 UILabel,例如使用 YYText 组件。YYText 是 YYKit 的一个组件,它是一个功能强大的 iOS 文本框架,用于显示和编辑富文本。它具有高性能的异步文本布局和渲染,并且扩展了 CoreText 的属性,提供了更多的文本效果。你可以使用 NSMutableAttributedString 来创建富文本字符串,并将其设置给 UILabel 的 attributedText 属性,以实现降价信息的显示。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [CDMarkdownKit:广泛的Swift框架,提供简单且可自定义的markdown解析](https://download.csdn.net/download/weixin_42099087/15035498)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [YYText:用于显示和编辑富文本的 iOS 文本框架-开源](https://download.csdn.net/download/weixin_42116672/20385582)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [GitHub - ElvisCen/PPCounter: 一款简单实用的数字加减动画,支持UILabel、UIButton显示](https://blog.csdn.net/weixin_36159799/article/details/117478907)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值