UIlabel

时间:2018-03-31 01:04:12

标签: ios swift uilabel nsattributedstring

我想在UILabel中显示倒计时器,但是当我更新计时器时,下一句话/单词位置会发生变化。计时器向左,向右移动后完成句子。 enter image description here 我想修复计时器的宽度(4:47),以便只更新计时器值而不改变任何其他单词的位置。任何想法都将有助于解决这个问题。我不能使用三个标签,因为文字是多行的。

以下是我正在使用的代码:

override func viewDidLoad() {
    super.viewDidLoad()

    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {[weak self] timer in
        self?.updateText()
        if let time = self?.reservedTimeInSeconds, time < 0 {
            timer.invalidate()
            self?.reservedTimeInSeconds = 300
        }
    }
}

func updateText() {
    let minutes: Int = self.reservedTimeInSeconds / 60
    let seconds: Int = self.reservedTimeInSeconds % 60
    let timer = String(format: "%d:%02d", minutes, seconds)

    self.textLabel.text = "Price valid for: \(timer). All prices inclusive of 3% gst."

    self.reservedTimeInSeconds -= 1
}

我尝试使用属性字符串,但没有运气,这个代码有点工作,但当我尝试设置自定义字体和字体大小,它打破。

func updateText() {
    let minutes: Int = self.reservedTimeInSeconds / 60
    let seconds: Int = self.reservedTimeInSeconds % 60
    let timer = String(format: "%d:%02d", minutes, seconds)
    let html = "<div>%@ <div style=\"color: %@;text-align: center;display: inline-block; overflow: hidden;\">%@</div>. %@</div>"
    let htmlFilledString = String(format: html, "Price valid for: ", "green", timer, "All price inclusive of 3% gst. All price inclusive of 3% gst")
    self.textLabel.attributedText = htmlFilledString.html2AttributedString

    self.reservedTimeInSeconds -= 1
}


extension Data {
    var html2AttributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            print("error:", error)
            return  nil
        }
    }
    var html2String: String {
        return html2AttributedString?.string ?? ""
    }
}

extension String {
    var html2AttributedString: NSAttributedString? {
        return Data(utf8).html2AttributedString
    }
    var html2String: String {
        return html2AttributedString?.string ?? ""
    }
}

1 个答案:

答案 0 :(得分:1)

如果您不能使用三个标签,我认为您可以使用2个标签来解决此问题;)。

  • 在倒数计时器之前计算文本的宽度和高度。在这种情况下,它的价格对于&#34;有效。您可以使用以下扩展程序来执行此操作。

    extension String {
      func widthOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedStringKey.font: font];
        let size = self.size(withAttributes: fontAttributes);
        return size.width
      }
    
      func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedStringKey.font: font], context: nil)
        return boundingBox.height
      }
    }
    
  • 使用与UILabel相同的字体再创建一个countDownLabelmainLabel),将其设为绿色textColor
  • coundDownLabel重叠mainLabel
  • 而不是设置

    mainLabel.text = "Price valid for 4:36. All prices are inclusive of 9234% GST.";
    

    使用

    mainLabel.text = "Price valid for          . All prices are inclusive of 9234% GST.";
    
  • 最后,给countDown一个正确的前导和顶部约束。

    let displayedText = "Price valid valid valid valid for _counDownTimer_. All prices are inclusive of 9234% GST.";
    let labelWidth : CGFloat = 200;
    
    // Add main label
    let textLabel = UILabel.init();
    textLabel.translatesAutoresizingMaskIntoConstraints = false;
    textLabel.textColor = UIColor.darkGray;
    textLabel.numberOfLines = 0;
    textLabel.text = displayedText.replacingOccurrences(of: "_counDownTimer_", with: "         ");
    self.view.addSubview(textLabel);
    
    // Update constraints for |textLabel|
    textLabel.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true;
    textLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 10).isActive = true;
    textLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true;
    
    // Add timer label
    let countDownLabel = UILabel.init();
    countDownLabel.textColor = UIColor.green;
    countDownLabel.translatesAutoresizingMaskIntoConstraints = false;
    self.view.addSubview(countDownLabel);
    
    // Calculate position and update constraints of |countDownLabel|
    let timerTextRange = displayedText.range(of: "_counDownTimer_");
    let textBeforeTimer = displayedText.substring(to: (timerTextRange?.lowerBound)!);
    let textWidth = textBeforeTimer.widthOfString(usingFont: textLabel.font);
    let textHeight = textBeforeTimer.heightWithConstrainedWidth(width: labelWidth, font: textLabel.font);
    
    var leadingConstant = textWidth;
    let topConstant = textHeight - textLabel.font.lineHeight;
    
    let indexOfCountDownLine = NSInteger(textHeight / textLabel.font.lineHeight) - 1;
    
    if indexOfCountDownLine > 0 {
      leadingConstant = leadingConstant - CGFloat(indexOfCountDownLine) * labelWidth;
    }
    
    countDownLabel.topAnchor.constraint(equalTo: textLabel.topAnchor, constant: topConstant).isActive = true;
    countDownLabel.leadingAnchor.constraint(equalTo: textLabel.leadingAnchor, constant: leadingConstant).isActive = true;
    

<强>结果

enter link description here

有关详细信息,您可以查看我的演示报告here