Attributed Text Center Alignment

前端 未结 10 2445
故里飘歌
故里飘歌 2020-12-13 17:06

I have tried everything but cannot seem to center this text. Can someone please tell me where the error is.

NSMutableParagraphStyle *paragraphStyle = NSMutab         


        
相关标签:
10条回答
  • 2020-12-13 17:26

    In Swift 5

    let paragraph = NSMutableParagraphStyle()
    paragraph.alignment = .center
    textView.attributedText = NSAttributedString(string: "String",
                                                         attributes: [.paragraphStyle: paragraph])
    

    In Swift-4

    let paragraph = NSMutableParagraphStyle()
    paragraph.alignment = .center
    
    let attributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.paragraphStyle: paragraph]
    let attrString = NSAttributedString(string:"string", attributes: attributes)
    textView.attributedText =  attrString
    

    In Swift-3

    let paragraph = NSMutableParagraphStyle()
    paragraph.alignment = .center
    
    let attributes: [String : Any] = [NSParagraphStyleAttributeName: paragraph]
    let attrString = NSAttributedString(string:"string", attributes: attributes)
    textView.attributedText =  attrString
    
    0 讨论(0)
  • 2020-12-13 17:26

    In Swift 4

    let paragraph = NSMutableParagraphStyle()
    paragraph.alignment = .center
    
    textView.attributedText = NSAttributedString(string: "string",
                                             attributes: [.paragraphStyle: paragraph])
    
    0 讨论(0)
  • 2020-12-13 17:28

    Another way:

    Swift:

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center
    let attributedString = NSAttributedString(string: "This will be centered.", attributes: [ NSAttributedString.Key.paragraphStyle: paragraphStyle])
    

    Obj-C:

    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.alignment = NSTextAlignmentCenter;    
    NSAttributedString *attributedString =  [NSAttributedString.alloc initWithString:@"This will be centered." 
    attributes: @{NSParagraphStyleAttributeName:paragraphStyle}];
    
    0 讨论(0)
  • 2020-12-13 17:32

    In Swift

    let titleString = "title here"
    
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .Center
    
    let attributedString = NSAttributedString(
        string: titleString,
        attributes: [NSParagraphStyleAttributeName: paragraphStyle]
    )
    
    titleAttributedLabel.attributedText = attributedString
    
    0 讨论(0)
提交回复
热议问题