Подтвердить что ты не робот

Полужирная часть строки в UITextView swift

Вот текст:

@IBOutlet weak var legalText: UITextView!
let textToAppend = "TERMS OF SERVICE\nLast Updated: May 7, 2015\n\nPLEASE NOTE: The HIGO Terms of Service as stated below is effective as of the 'Last Updated' date above for any user who is browsing the HIGO website, or for any user who creates a HIGO account on or after that date."
legalText.text = legalText.text.stringByAppendingString(textToAppend)

Я хочу выделить "УСЛОВИЯ ОБСЛУЖИВАНИЯ" и "ПОЖАЛУЙСТА, ОБРАТИТЕ ВНИМАНИЕ: Условия обслуживания HIGO, как указано ниже, действуют с даты" Последнее обновление "выше для любого пользователя, просматривающего веб-сайт HIGO или для любого пользователя который создает учетную запись HIGO после или после этой даты".

Я пытаюсь использовать uilabel программно в uitextview, но не работает:

var termsofservice : UILabel = UILabel()
termsofservice.numberOfLines = 0
termsofservice.text = "TERMS OF SERVICE"
termsofservice.font = UIFont.boldSystemFontOfSize(20)
termsofservice.textAlignment = NSTextAlignment.Left;

var pleasenote : UILabel = UILabel()
pleasenote.numberOfLines = 0
pleasenote.text = "PLEASE NOTE: The HIGO Terms of Service as stated below is effective as of the 'Last Updated' date above for any user who is browsing the HIGO website, or for any user who creates a HIGO account on or after that date."
pleasenote.font = UIFont.boldSystemFontOfSize(20)
pleasenote.textAlignment = NSTextAlignment.Left;

let textToAppend = "\(termsofservice)\nLast Updated: May 7, 2015\n\n\(pleasenote)"

также попробуйте с ними, но не работает, он показывает только "УСЛОВИЯ ОБСЛУЖИВАНИЯ" и "последнее обновление..", не показывал "ПОЖАЛУЙСТА ЗАМЕТЬТЕ..."

var termsofservice = "TERMS OF SERVICE"
var normalText = "\n\nLast Updated: May 7, 2015"
var pleasenote  = "\n\nPLEASE NOTE: The HIGO Terms of Service as stated below is effective as of the 'Last Updated' date above for any user who is browsing the HIGO website, or for any user who creates a HIGO account on or after that date."

var attributedString = NSMutableAttributedString(string:normalText)

var attrs = [NSFontAttributeName : UIFont.boldSystemFontOfSize(15)]
var boldString = NSMutableAttributedString(string:pleasenote, attributes:attrs)
var boldString0 = NSMutableAttributedString(string:termsofservice, attributes:attrs)

boldString0.appendAttributedString(attributedString)
attributedString.appendAttributedString(boldString)
legalText.attributedText = boldString0

Как выделять эту часть строки?

Примечание: текст по-прежнему длинный и содержит большую часть строки, выделенной жирным шрифтом.

4b9b3361

Ответ 1

Обновлено для Swift 3

func attributedText() -> NSAttributedString {

    let string = "TERMS OF SERVICE\nLast Updated: May 7, 2015\n\nPLEASE NOTE: The HIGO Terms of Service as stated below is effective as of the 'Last Updated' date above for any user who is browsing the HIGO website, or for any user who creates a HIGO account on or after that date." as NSString

    let attributedString = NSMutableAttributedString(string: string as String, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 15.0)])

    let boldFontAttribute = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 15.0)]

    // Part of string to be bold
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "TERMS OF SERVICE"))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "PLEASE NOTE:"))

    // 4
    return attributedString
}

И установите текст атрибута в текстовое представление как:

legalText.attributedText = attributedText()

Ответ 2

Более того, вы можете пойти дальше и использовать эту функцию 1 в своем арсенале, в файле, подобном Constants.swift, а затем вы можете объединять слова в любой строке, неоднократно вызывая всего лишь ONE LINE кода:

Чтобы перейти в файл без класса, например, constants.swift в моем случае:

import Foundation
import UIKit

func addBoldText(fullString: NSString, boldPartOfString: NSString, font: UIFont!, boldFont: UIFont!) -> NSAttributedString {
    let nonBoldFontAttribute = [NSAttributedString.Key.font:font!]
    let boldFontAttribute = [NSAttributedString.Key.font:boldFont!]
    let boldString = NSMutableAttributedString(string: fullString as String, attributes:nonBoldFontAttribute)
    boldString.addAttributes(boldFontAttribute, range: fullString.range(of: boldPartOfString as String))
    return boldString
}

Затем вы можете просто вызвать эту одну строку кода для любого UILabel:

let normalFont = UIFont(name: "INSERT FONT NAME", size: 14)
let boldFont = UIFont(name: "INSERT BOLD FONT NAME", size: 14)
self.UILabel.attributedText = addBoldText("Check again in 30 DAYS to find more friends", boldPartOfString: "30 DAYS", font: normalFont!, boldFont: boldFont!)

Ответ 3

Обновление Swift 3 (из ответа @Hamza Ansari)

func attributedText()-> NSAttributedString
{
    let string = "TERMS OF SERVICE\nLast Updated: May 7, 2015\n\nPLEASE NOTE: The HIGO Terms of Service as stated below is effective as of the 'Last Updated' date above for any user who is browsing the HIGO website, or for any user who creates a HIGO account on or after that date." as NSString

    let attributedString = NSMutableAttributedString(string: string as String, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 15.0)])

    let boldFontAttribute = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 15.0)]

    // Part of string to be bold
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "TERMS OF SERVICE"))
    attributedString.addAttributes(boldFontAttribute, range: string.range(of: "PLEASE NOTE:"))

    // 4
    return attributedString
}

Ответ 4

Обновление Swift 4.2

func addBoldText(fullString: String, boldPartOfString: String, baseFont: UIFont, boldFont: UIFont) -> NSAttributedString {

    //1
    let baseFontAttribute = [NSAttributedString.Key.font : baseFont]
    let boldFontAttribute = [NSAttributedString.Key.font : boldFont]

    //2
    let attributedString = NSMutableAttributedString(string: fullString, attributes: baseFontAttribute)

    //3. Note if 'boldPartOfString' is not a substring of 'fullString', enitre 'fullString' will be formatted with 'boldFont'
    attributedString.addAttributes(boldFontAttribute, range: NSRange(fullString.range(of: boldPartOfString) ?? fullString.startIndex..<fullString.endIndex, in: fullString))

    //4
    return attributedString
}