首页 > 解决方案 > 在换行符后附加字符串

问题描述

在此处输入图像描述

我想为 NSAttributedString 实现这个(如上图所示)换行和连接。第二个城市,在这种情况下,巴黎应该从顶部开始,但它从德国的右侧开始,因为德国从新线开始,这就是为什么巴黎被附加在德国的右侧而不是从顶部开始的原因。任何帮助,将不胜感激。

以下是我的代码:

    /// Flight Attributed String
    var flightAttributedString = NSMutableAttributedString(string: "");

    /// From City
    let fromCityAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10.0, weight: .medium)];
    let fromCity = NSMutableAttributedString(string: "\((self.route?.fromCity)!)  ", attributes: fromCityAttributes);

    /// From Country
    let fromCountryAttributes = [NSAttributedString.Key.foregroundColor : kAppSecondryIconColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 8.0)];
    let fromCountry = NSMutableAttributedString(string: "\n\((self.route?.fromCountry)!)", attributes: fromCountryAttributes);

    /// From City Complete
    fromCity.append(fromCountry);

    /// To City
    let toCityAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10.0, weight: .medium)] as [NSAttributedString.Key : Any]
    let toCity = NSMutableAttributedString(string: "\((self.route?.toCity)!)  ", attributes: toCityAttributes);

    /// To Country
    let toCountryAttributes = [NSAttributedString.Key.foregroundColor : kAppSecondryIconColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 8.0)];
    let toCountry = NSMutableAttributedString(string: "\n\((self.route?.toCountry)!)", attributes: toCountryAttributes);

    /// To City Complete
    toCity.append(toCountry);
    // print("toCity.accessibilityFrame: \(toCity.accessibilityFrame)");

    /// Plain Icon
    let imgAttachment = NSTextAttachment()
    imgAttachment.image = UIImage(named: "iconAirplane.png")
    imgAttachment.bounds = CGRect(x: 0, y: -5, width: 25.0, height: 25.0)
    let imgAirplane = NSAttributedString(attachment: imgAttachment)

    /// Making Complete Flight String
    flightAttributedString.append(fromCity);
    flightAttributedString.append(imgAirplane);
    flightAttributedString.append(toCity);

    /// Draw the result in a lblFlight
    // self.lblFlight.lineBreakMode = .byWordWrapping;
    self.lblFlight.attributedText = flightAttributedString;

标签: iosswiftnsattributedstring

解决方案


我个人会在这里使用堆栈视图,它肯定会给你更多的灵活性。

这是最终结果:

在此处输入图像描述

实现将是这样的:

import UIKit

class ViewController: UIViewController {

    private let flightBoardView: FlightBoardView = {
        $0.translatesAutoresizingMaskIntoConstraints = false
        return $0
    }(FlightBoardView())

    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
        view.backgroundColor = .white
    }

    private func setup() {
        setupViews()
        setupConstraints()
    }

    private func setupViews() {
        flightBoardView.set(fromCountry: "Germany", fromCity: "Frankfurt", toCountry: "France", toCity: "Paris")
        view.addSubview(flightBoardView)
    }

    private func setupConstraints() {
        flightBoardView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        flightBoardView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    }
}

FlightBoardView可能是一个子类UIView(如果你想稍后在代码中的某个地方重用它并避免重复),看起来像这样:

class FlightBoardView: UIView {

    private lazy var departureStackView: UIStackView = {
        $0.distribution = .fill
        $0.alignment = .leading
        $0.axis = .vertical
        $0.spacing = 5
        $0.translatesAutoresizingMaskIntoConstraints = false
        return $0
    }(UIStackView(arrangedSubviews: [fromCountryLabel, fromCityLabel]))

    private lazy var destinationStackView: UIStackView = {
        $0.distribution = .fill
        $0.alignment = .leading
        $0.axis = .vertical
        $0.spacing = 5
        $0.translatesAutoresizingMaskIntoConstraints = false
        return $0
    }(UIStackView(arrangedSubviews: [toCountryLabel, toCityLabel]))

    private lazy var containerStackView: UIStackView = {
        $0.distribution = .fill
        $0.alignment = .center
        $0.axis = .horizontal
        $0.spacing = 20
        $0.translatesAutoresizingMaskIntoConstraints = false
        return $0
    }(UIStackView(arrangedSubviews: [departureStackView, planeImageView, destinationStackView]))

    private let fromCountryLabel: UILabel = {
        $0.textColor = .black
        $0.font = UIFont.systemFont(ofSize: 30)
        $0.translatesAutoresizingMaskIntoConstraints = false
        return $0
    }(UILabel())

    private let fromCityLabel: UILabel = {
        $0.textColor = .lightGray
        $0.font = UIFont.systemFont(ofSize: 15)
        $0.translatesAutoresizingMaskIntoConstraints = false
        return $0
    }(UILabel())

    private let toCountryLabel: UILabel = {
        $0.textColor = .black
        $0.font = UIFont.systemFont(ofSize: 30)
        $0.translatesAutoresizingMaskIntoConstraints = false
        return $0
    }(UILabel())

    private let toCityLabel: UILabel = {
        $0.textColor = .lightGray
        $0.font = UIFont.systemFont(ofSize: 15)
        $0.translatesAutoresizingMaskIntoConstraints = false
        return $0
    }(UILabel())

    private let planeImageView: UIImageView = {
        $0.contentMode = .scaleAspectFit
        $0.image = UIImage(named: "airplane")?.withRenderingMode(.alwaysTemplate)
        $0.tintColor = .systemBlue
        $0.translatesAutoresizingMaskIntoConstraints = false
        return $0
    }(UIImageView())

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder: NSCoder) {
        fatalError()
    }

    private func setup() {
        addSubview(containerStackView)
        NSLayoutConstraint.activate([
            containerStackView.topAnchor.constraint(equalTo: topAnchor),
            containerStackView.leftAnchor.constraint(equalTo: leftAnchor),
            containerStackView.bottomAnchor.constraint(equalTo: bottomAnchor),
            containerStackView.rightAnchor.constraint(equalTo: rightAnchor),
            planeImageView.widthAnchor.constraint(equalToConstant: 50),
            planeImageView.heightAnchor.constraint(equalTo: planeImageView.widthAnchor),
        ])
    }

    func set(fromCountry: String, fromCity: String, toCountry: String, toCity: String) {
        fromCountryLabel.text = fromCountry
        fromCityLabel.text = fromCity
        toCountryLabel.text = toCountry
        toCityLabel.text = toCity
    }
}

当然,如果您愿意,您可以对 Storyboard 和 xib 文件执行相同的操作,但至少这为您提供了一个工作示例,您可以根据需要进行调整。

我还添加了set(fromCountry:fromCity:toCountry:toCity:)允许您从父视图轻松更改数据的方法。


推荐阅读