Swift3.0 設定UILabel檔案行間距 含oc版
阿新 • • 發佈:2019-02-10
UILabel實用設定行間距程式碼,直接上程式碼
swift:
fileprivate func createUI(){
let subLabel = UILabel()
subLabel.font = UIFont(name: "EuphemiaUCAS", size: 19.0)
subLabel.numberOfLines = 0
subLabel.backgroundColor = UIColor.orange
let subStr = "for-in 語句在迴圈開始前會呼叫集合表示式的 generate 方法來獲取一個實現了 GeneratorType 協議的型別的值。接下來迴圈開始,反覆呼叫該值的 next() 方法。如果其返回值不是 None,它將會被賦給“項”,然後執行迴圈體語句,執行完畢後回到迴圈開始處,繼續重複這一過程;否則,既不會賦值也不會執行迴圈體語句,for-in 語句至此執行完畢。"
subLabel.attributedText = self .getAttributeStringWithString(subStr, lineSpace: 8.00)
subLabel.centerX = self.view.centerX
let fontSize = CGSize(width: kScreenW, height: subLabel.font.lineHeight)
let rect:CGSize = subStr.boundingRect(with: fontSize, options: NSStringDrawingOptions.usesLineFragmentOrigin , attributes: [NSFontAttributeName: subLabel.font], context: nil).size;
subLabel.frame = CGRect(x: 15, y: 100, width: kScreenW, height: 200)
subLabel.size = CGSize(width: rect.width-15, height: rect.height)
subLabel.sizeToFit()
self.view .addSubview(subLabel)
}
fileprivate func getAttributeStringWithString(_ string : String,lineSpace:CGFloat
) -> NSAttributedString{
let attributedString = NSMutableAttributedString(string: string)
let paragraphStye = NSMutableParagraphStyle()
//調整行間距
paragraphStye.lineSpacing = lineSpace
let rang = NSMakeRange(0, CFStringGetLength(string as CFString!))
attributedString .addAttribute(NSParagraphStyleAttributeName, value: paragraphStye, range: rang)
return attributedString
}
oc:
UILabel * subLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, MainLabel.bottom+15*__kRatio, __kScreenWidth, 40)];
subLabel.text = @"for-in 語句在迴圈開始前會呼叫集合表示式的 generate 方法來獲取一個實現了 GeneratorType 協議的型別的值。接下來迴圈開始,反覆呼叫該值的 next() 方法。如果其返回值不是 None,它將會被賦給“項”,然後執行迴圈體語句,執行完畢後回到迴圈開始處,繼續重複這一過程;否則,既不會賦值也不會執行迴圈體語句,for-in 語句至此執行完畢。";
// 調整行間距
subLabel.attributedText = [self getAttributedStringWithString:subLabel.text lineSpace:8];
subLabel.textColor = kColorA6A6A6;
subLabel.font = _kFontMain;
subLabel.numberOfLines =0;
subLabel.textAlignment = NSTextAlignmentCenter;
subLabel.size = [subLabel.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, subLabel.font.lineHeight)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName : subLabel.font}
context:nil].size;
subLabel.centerX = MainLabel.centerX;
[subLabel sizeToFit];
[_topView addSubview:subLabel];
// 調整行間距
-(NSAttributedString *)getAttributedStringWithString:(NSString *)string lineSpace:(CGFloat)lineSpace {
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = lineSpace; // 調整行間距
NSRange range = NSMakeRange(0, [string length]);
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
return attributedString;
}