centering text in a UILabel with an NSAttributedString

后端 未结 3 650
清歌不尽
清歌不尽 2021-02-02 06:57

Going through some basic improvements to a application I am working on. Still new to the iOS swift development scene. I figured that the lines of text in my code would automatic

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-02 07:03

    You can use this utility function to do all common configuration for label

    
        @discardableResult
        public func DULabel(text: String, frame: CGRect = .zero, parent:UIView? = nil , font:UIFont, textColor:UIColor = .black, numOfLines:Int = 0 ,textAlignment: NSTextAlignment = .center,lineSpaceing:CGFloat = 0, cb: ((UILabel)->Void)? = nil  )-> UILabel! {
          let label = UILabel()
          label.frame = frame
          label.font = font
          label.textColor = textColor
          label.textAlignment = textAlignment
          label.numberOfLines = numOfLines
          if( lineSpaceing == 0 ){
            label.text = text
          }
          else {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = lineSpaceing
            paragraphStyle.alignment = textAlignment
            let attrString = NSMutableAttributedString(string: text)
            attrString.addAttribute(.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
            label.attributedText = attrString
          }
          if let parent = parent {
            parent.addSubview(label)
          }
          cb?(label)
          return label
        }
    
    

提交回复
热议问题