Programing

UILabel 줄 간격 설정

lottogame 2020. 8. 18. 08:06
반응형

UILabel 줄 간격 설정


여러 줄의 줄 간격 (줄 간격)을 어떻게 수정할 수 UILabel있습니까?


편집 : 분명히 NSAttributedStringiOS 6 이상에서 할 것입니다. 를 사용 NSString하여 레이블의 텍스트를 설정하는 대신를 만들고 여기에 NSAttributedString속성을 설정 한 다음 .attributedText레이블에서 로 설정하십시오 . 원하는 코드는 다음과 같습니다.

NSMutableAttributedString* attrString = [[NSMutableAttributedString  alloc] initWithString:@"Sample text"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:24];
[attrString addAttribute:NSParagraphStyleAttributeName
    value:style
    range:NSMakeRange(0, strLength)];
uiLabel.attributedText = attrString;

NSAttributedString은의 옛 attributedStringWithString는 같은 일을했다,하지만 지금은 사용되지 않습니다.

역사적인 이유로 내 원래 대답은 다음과 같습니다.

짧은 대답 : 할 수 없습니다. 텍스트 줄 사이의 간격을 변경하려면 UILabel자신의 하위 클래스를 만들고 롤링하거나 drawTextInRect여러 레이블을 만들거나 다른 글꼴을 사용해야합니다 (아마도 특정 줄 높이에 맞게 편집 된 글꼴, Phillipe의 답변 참조).

긴 답변 : 인쇄 및 온라인 세계에서 텍스트 줄 사이의 공간은 "리딩"으로 알려져 있습니다 ( '제목'과 운율, 수십 년 전에 사용 된 납 금속에서 비롯됨). Leading은의 읽기 전용 속성으로 UIFont, 4.0에서 더 이상 사용되지 않고 lineHeight. 내가 아는 한, 다음과 같은 특정 매개 변수 세트로 글꼴을 만들 수있는 방법이 없습니다 lineHeight. 시스템 글꼴과 추가 한 사용자 지정 글꼴을 얻을 수 있지만 설치 한 후에는 조정할 수 없습니다.

에도 간격 매개 변수가 없습니다 UILabel.

UILabel의 동작에 특별히 만족스럽지 않으므로 자신의 하위 클래스를 작성하거나 타사 라이브러리를 사용하는 것이 좋습니다. 그러면 글꼴 선택과 무관하게 동작이 가능하며 가장 재사용 가능한 솔루션이됩니다.

에서 더 많은 유연성 있었으면 UILabel좋겠습니다. 잘못된 것으로 입증되어 기쁩니다!


iOS 6부터 UILabel에 속성 문자열을 설정할 수 있습니다.

NSString *labelText = @"some text"; 
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:40];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
cell.label.attributedText = attributedString ;

스토리 보드에서 줄 간격을 제어 할 수 있습니다.

중복 질문


Interface Builder에서 :

enter image description here

프로그래밍 방식 :

SWift 4

레이블 확장 사용

extension UILabel {

    func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {

        guard let labelText = self.text else { return }

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpacing
        paragraphStyle.lineHeightMultiple = lineHeightMultiple

        let attributedString:NSMutableAttributedString
        if let labelattributedText = self.attributedText {
            attributedString = NSMutableAttributedString(attributedString: labelattributedText)
        } else {
            attributedString = NSMutableAttributedString(string: labelText)
        }

        // Line spacing attribute
        attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))

        self.attributedText = attributedString
    }
}

이제 추가 전화 번호 정보 기능

let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"

// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) .  // try values 1.0 to 5.0

// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0


또는 라벨 인스턴스 사용 (결과를 보려면이 코드를 복사하고 실행하기 만하면됩니다)

let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40

// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))

// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))

label.attributedText = attrString

스위프트 3

let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString

My solution was to patch the font file itself and fix its line height definitely. http://mbauman.net/geek/2009/03/15/minor-truetype-font-editing-on-a-mac/

I had to modify 'lineGap', 'ascender', 'descender' in the 'hhea' block (as in the blog example).


This guy created a class to get line-height (without using CoreText, as MTLabel library) : https://github.com/LemonCake/MSLabel


Best thing I found is: https://github.com/mattt/TTTAttributedLabel

It's a UILabel subclass so you can just drop it in, and then to change the line height:

myLabel.lineHeightMultiple = 0.85;
myLabel.leading = 2;

I've found 3rd Party Libraries Like this one:

https://github.com/Tuszy/MTLabel

To be the easiest solution.


Here's some swift-code for you to set the line spacing programmatically

let label = UILabel()

let attributedText = NSMutableAttributedString(string: "Your string")
let paragraphStyle = NSMutableParagraphStyle()

//SET THIS:
paragraphStyle.lineSpacing = 4
//OR SET THIS:
paragraphStyle.lineHeightMultiple = 4

//Or set both :)

let range = NSMakeRange(0, attributedText.length)
attributedText.addAttributes([NSParagraphStyleAttributeName : paragraphStyle], range: range)
label.attributedText = attributedText

Of course, Mike's answer doesn't work if you pass the string programmatically. In this case you need to pass a attributed string and change it's style.

NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:@"Your \nregular \nstring"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:4];
[attrString addAttribute:NSParagraphStyleAttributeName
                   value:style
                   range:NSMakeRange(0, attrString.length)];
_label.attributedText = attrString;

참고URL : https://stackoverflow.com/questions/3880526/set-uilabel-line-spacing

반응형