【问题标题】:NSAttributedString on UIButtonUIButton 上的 NSAttributedString
【发布时间】:2018-01-07 22:31:18
【问题描述】:
let strNo = "2222555" // size 18, this should be bold

let remainingStr = "Call to" + "\(strNo)" + "Number" 

现在,在我的 UIButton 中,说按钮,How to set this title "Call to 2222555 number" 我需要根据设备更改大小,所以我必须通过编码来完成。

更新

我需要如下图。

并且需要通过编码改变标题的大小。上面的截图来自 iPhone 7,在 iPhone 5 中它变得更大,在 iPad 中它变得更小,所以我必须根据需要设置标题的大小。

任何帮助都将不胜感激。

谢谢

【问题讨论】:

  • 改变大小的意思是——字体大小,否则
  • 是字体大小..
  • 不,这不是我的答案,数字2222555应该是粗体,剩下的字符串应该是正常的,我需要通过编码来完成,可以通过xcode故事板中的属性部分,但它将为每个设备固定,这就是为什么我需要通过编码来做到这一点,以便我可以根据设备进行更改,并且属性文本字体不会通过这样做来简单地更改。
  • 你试过什么?您的属性字符串代码在哪里?请展示您的尝试。

标签: ios swift3 uibutton nsmutableattributedstring


【解决方案1】:

我挣扎了几天找到了答案。而且很简单。

guard
            let font1 = UIFont(name: "HelveticaNeue-Bold", size: 22),
            let font2 = UIFont(name: "HelveticaNeue-Medium", size: 22)  else { return }

        let dict1:[String:Any] = [
            //            NSUnderlineStyleAttributeName:NSUnderlineStyle.styleSingle.rawValue,
            NSFontAttributeName:font2,
            NSParagraphStyleAttributeName:style,
            NSForegroundColorAttributeName: UIColor.white
        ]

        let dict2:[String:Any] = [
            //            NSUnderlineStyleAttributeName:NSUnderlineStyle.styleNone.rawValue,
            NSFontAttributeName:font1,
            NSParagraphStyleAttributeName:style,
            NSForegroundColorAttributeName: UIColor.white,
            //            NSFontAttributeName: UIFont.boldSystemFont(ofSize: 20)
        ]

        let dict3:[String:Any] = [
            //            NSUnderlineStyleAttributeName:NSUnderlineStyle.styleNone.rawValue,
            NSFontAttributeName:font2,
            NSParagraphStyleAttributeName:style,
            NSForegroundColorAttributeName: UIColor.white
        ]

        let dict4:[String:Any] = [
            //            NSUnderlineStyleAttributeName:NSUnderlineStyle.styleNone.rawValue,
            NSFontAttributeName:font1,
            NSParagraphStyleAttributeName:style,
            NSForegroundColorAttributeName: UIColor.white
        ]

        let attString = NSMutableAttributedString()
        attString.append(NSAttributedString(string: "Call to", attributes: dict1))
        attString.append(NSAttributedString(string: " 2222555 ", attributes: dict2))
        attString.append(NSAttributedString(string: " To Book Your Skip ", attributes: dict3))
        attString.append(NSAttributedString(string: "NOW", attributes: dict4))

        btnCall.setAttributedTitle(attString, for: .normal)

而且它按预期完美运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2014-02-20
    • 2011-08-11
    • 2015-02-01
    • 2016-11-11
    • 1970-01-01
    相关资源
    最近更新 更多