簡體   English   中英

UIlabel中單詞的固定寬度(倒數計時器3:45)

[英]Fixed width for an word (countdown timer 3:45) in UIlabel

我想在UILabel中顯示倒數計時器,但是當我更新計時器時,下一個句子/單詞的位置就會改變。 計時器向左,向右移動后的完整句子。 在此處輸入圖片說明 我想固定timer(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 ?? ""
    }
}

如果您不能使用三個標簽,我想您可以使用2個標簽來解決此問題;)。

  • 在倒數計時器之前計算文字的寬度和高度。 在這種情況下,它是“價格有效”。 您可以使用以下擴展名來做到這一點。

     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 } } 
  • 再創建一個UILabelcountDownLabel用相同的字體) mainLabel ,給它綠色的textColor
  • 使coundDownLabelmainLabel重疊。
  • 代替設定

     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; 

結果

在此處輸入鏈接說明

有關更多詳細信息,您可以在此處查看我的演示存儲庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM