标签中的图片(Swift)

时间:2017-11-21 17:57:43

标签: ios swift xcode

我有代码在计算器中显示历史记录,但符号(+, - ,×,÷)取自“案例”( Photo 1

如何制作,以便在历史记录中,我设置的图片( Photo 2 )显示标志(+, - ,×,÷)

**Photo 1**

**Photo 2**

@IBAction func equalitySignPressed(sender: UIButton) {
    if stillTyping {
        secondOperand = currentInput
    }
    dotIsPlaced = false

        addHistory(text: operationSign + displayResultLabel.text!)

    switch operationSign {

    case "+":
        operateWithTwoOperands{$0 + $1}
    case "-":
        operateWithTwoOperands{$0 - $1}
    case "×":
        operateWithTwoOperands{$0 * $1}
    case "÷":
        operateWithTwoOperands{$0 / $1}
    default: break
    }
}

历史:

func addHistory(text: String){
    //Add text
    resultLabelText.text =  resultLabelText.text! + "" + text
}

2 个答案:

答案 0 :(得分:1)

您可以制作符号图像并使用NSTextAttachment构建NSAttributedAtring,用您的符号图像替换字符串中的文本和相应的NSTextAttachment。这是一个带有一个图像的示例游乐场,但您可以轻松地将更多图像添加到字典中,以用图像替换所有其他符号:

import PlaygroundSupport
import UIKit

class V: UIViewController {
    let label = UILabel()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(label)
        label.textColor = .red

    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let expression = "5 + 5"
        let plusAttachment = NSTextAttachment()
        plusAttachment.image = UIImage(named: "star.png")
        let plusString = NSAttributedString(attachment: plusAttachment)
        let substitutions: [Character: NSAttributedString] = ["+": plusString]
        let attributedExpression = NSMutableAttributedString()
        for character in expression {
            if let substitution = substitutions[character] {
                attributedExpression.append(substitution)
            } else {
                attributedExpression.append(NSAttributedString(string: String(character)))
            }
        }
        label.attributedText = attributedExpression
        label.sizeToFit()

    }
}

PlaygroundPage.current.liveView = V()

答案 1 :(得分:0)

我建议您使用表情符号字体显示带有边框的数学符号。使用该字体创建NSAttributedString并将其设置为标签attributedText

关于如何使用自定义字体,您可以参考here或只搜索SO。关于这个主题有很多问题。

我也看到你希望文本是粗体的,也可以使用属性字符串来完成。

或者,您可以将这些很酷的数学符号添加为NSAttributedString的附件,但我怀疑这些大小是否正确很容易。

相关问题