IOS Multiple right and left align on same line

前端 未结 3 740
南笙
南笙 2020-12-10 06:26

I want to write on the same line of my tableview cell detailTextLabel.

For example Left string right string.

I\'m doing this :

3条回答
  •  误落风尘
    2020-12-10 06:53

    It would be better to create a custom cell with 2 labels but if for some reason you still want to have it in a single label then below is a solution. If you know what is the height of the line then you can use paragraphSpacingBefore to do something like in code below. Note that it does not work when UILabel numberOfLines is set to 1 so you must set numberOfLines to for example 0:

    let text = "left\nright"
    let at = NSMutableAttributedString(string: text)
    let p1 = NSMutableParagraphStyle()
    let p2 = NSMutableParagraphStyle()
    p1.alignment = .left
    p2.alignment = .right
    p2.paragraphSpacingBefore = -label.font.lineHeight
    at.addAttribute(.paragraphStyle, value: p1, range: NSRange(location: 0, length: 4))
    at.addAttribute(.paragraphStyle, value: p2, range: NSRange(location: 4, length: 6))
    label.numberOfLines = 0
    label.attributedText = at
    

提交回复
热议问题