【问题标题】:How to Customize price button text in swift, iOS [closed]如何在 swift,iOS 中自定义价格按钮文本 [关闭]
【发布时间】:2019-04-26 06:34:30
【问题描述】:

我有 2 个UIButton,如下图所示。在这里我需要为两者自定义完全相同,意思是文本,我怎么能这样做。

建议我如何在情节提要中(使用标签/视图..)或以编程方式执行此操作。如果标签或按钮文本如图所示,请指导我使用NSAttributtedstring 的一些代码。

【问题讨论】:

  • 只需在情节提要中使用简单的 UI。不要过度复杂化。
  • 选择是我们的,我的建议是使用 NSMutableAttributedString 作为上标(使用 UIButton)。并将 UIlabel 与变换一起使用(例如:stackoverflow.com/questions/41063225/…
  • @RJE,我必须动态使用这些按钮,意味着价格会根据地区而变化。所以我不能简单地使用图像来自定义它..
  • 我的意思是要么使用上面 Anbu 建议的带有 NSAttributedString 的按钮,要么使用 UIViews 和 UILabels 并根据接收到的值更改它们。无论如何,它是一个带有故事板的简单 UI 安排。

标签: ios swift button xcode-storyboard


【解决方案1】:

您可以在 func 下使用它:

extension UILabel {
    func setAttributes(price : String) {
        let font:UIFont? = UIFont.boldSystemFont(ofSize: 22)
        let fontSuper:UIFont? = UIFont.boldSystemFont(ofSize: 15)
        let aDotRange = (price as NSString).range(of: ".")

        let attString:NSMutableAttributedString = NSMutableAttributedString(string: price, attributes: [.font:font!])

        attString.setAttributes([.font:fontSuper!,.baselineOffset:5], range: NSRange(location:0,length:1))

        attString.setAttributes([.font:fontSuper!,.baselineOffset:5],
                                range: NSRange(location:aDotRange.location,length:4))
        attString.setAttributes([.font:font!],
                                range: NSRange(location:1,length:aDotRange.location - 1 ))
        attString.setAttributes([.font:fontSuper!],
                                range: NSRange(location:aDotRange.location + 4,
                                               length: (price.count) - (aDotRange.location + 4) ))
        self.attributedText = attString
    }

}

虚拟代码

lblPrice.setAttributes(price: "$249.99 / mon")
lblPrice.layer.cornerRadius = 4
lblPrice.layer.borderWidth = 1.0
lblPrice.layer.borderColor = UIColor.blue.cgColor

lblPrice2.setAttributes(price: "$999.99 / 6 mo")
lblPrice2.layer.cornerRadius = 4

输出

【讨论】:

  • 它显示在你的虚拟代码第一行中使用了未解析的标识符价格..如何解决这个问题?
  • @Aleesha 立即查看。
  • 非常感谢.. 快完成了!!.. 工作正常...
【解决方案2】:

您可以使用UIViewsUILabels 来设计按钮并将tapGestures 添加到UIViews 以进行用户交互。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 2011-09-02
    • 2018-09-21
    • 1970-01-01
    • 2017-10-11
    • 2014-12-07
    • 1970-01-01
    相关资源
    最近更新 更多