美文网首页swift
迟到的Swift入门 - UILabel

迟到的Swift入门 - UILabel

作者: 刘_小_二 | 来源:发表于2020-09-03 13:36 被阅读0次

    UILabel教程

    1.UILabel基础教程

    1. 创建文本

    let label = UIlabel()
    
    let label = UILabel(frame: CGRectMake(10, 100, 300, 30))
    
    let artLabel: UILabel = UILabel(frame: CGRectMake(100,100,100,100))
    

    例子:

    //创建时设置frame
    let label = UILabel(frame: CGRectMake(10, 100, 300, 30))
    //添加到self.view上才会显示出来
    self.view.addSubview(label)
    
    //先创建,后设置frame
    let label = UILabel()
    label.frame = CGRectMake(10, 100, 300, 30)
    self.view.addSubview(label)
    

    2.文本属性配置

    //设置tag值
    label.tag = 51
    
    //通过tag值获取
    self.view.viewWithTag(51) as! UILabel
    
    //设置背景色
    label.backgroundColor = UIColor.greenColor()
    
    //设置字体颜色
    label.textColor = UIColor.redColor()
    
    //设置字体大小
    label.font = UIFont.systemFontOfSize(16)//第一种
    label.font = UIFont(name: "Helvetica_Bold", size: 16)//第二种
    
    //设置文本对齐方式,默认左对齐
    label.textAlignment = NSTextAlignment.Right
    
    //设置要显示的文本
    label.text = "I am a label"
    
    //打印label的文本,因为label.text为String?,所以要加!
    let labelString = label.text!
    
    // 交互,默认是false
    label.userInteractionEnabled = true
    
    //可变,默认是true
    label.enabled = false
    
    //行数,设置为0代表无限制的意思
    label.numberOfLines = 0
    
     //设置高亮(默认是falue),及其颜色
     label.highlighted = true
     label.highlightedTextColor = UIColor.blueColor()
    

    3.富文本设置

    //富文本设置
    /**
      @param NSMakeRange(0,3) 0是起始位置,3是长度
    */
    let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "超人爱睡觉看夏洛克逛博客写文章运动打球打游戏啊啊啊啊啊")
    
    //设置字体
    attributeString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Bold",size: 26)!, range: NSMakeRange(0,3))
    
    //设置字体颜色
    attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, 3))
    
    //设置背景颜色
    attributeString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellowColor(), range: NSMakeRange(3, 3))
    artLabel.numberOfLines = 0
    artLabel.attributedText = attributeString
    artLabel.baselineAdjustment = .AlignCenters//没什么变化
    

    4.自适应高度

    /**
    UILabel自适应高度
            
    @param CGFLOAT_MAX 无限大
    @param NSStringDrawingUsesLineFragmentOrigin 绘制文本使用
    */
    let size = (artLabel.text! as NSString).boundingRectWithSize(CGSizeMake(100, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(16)], context: nil)
    
    artLabel.frame = CGRectMake(100, 100, size.width, size.height)
    

    相关文章

      网友评论

        本文标题:迟到的Swift入门 - UILabel

        本文链接:https://www.haomeiwen.com/subject/fmgnsktx.html