0

I want to show countdown timer in UILabel but when I am updating the timer next sentence/ word position is getting changed. Complete sentence after timer is moving left, right. enter image description here I want to fix the width for timer(4:47) so that only timer value should update without changing position of any other word. Any Idea will be help full to fix this. I can't use three labels because text is multiline.

Here is the code I am using:

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
}

I tried using attributed string but no luck, this code somewhat working but when I trying to set custom font and font size its breaking.

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 ?? ""
    }
}
trungduc
  • 11,926
  • 4
  • 31
  • 55
kmithi1
  • 1,737
  • 2
  • 15
  • 18
  • https://stackoverflow.com/questions/11583581/how-to-keep-2-different-fonts-within-the-same-uitextfield-or-uitextview – Nerdy Bunz Mar 31 '18 at 01:52
  • @kmithi Does my answer work guy? – trungduc Mar 31 '18 at 15:48
  • @trungduc Yah some what useful, just had to change y position so that if first text also become multiline then timer comes at right place. Problem is my app support multiple language and in some language string are really hudge. – kmithi1 Mar 31 '18 at 18:41
  • @kmithi I have updated my answer with solution for multiple line label. Please check again. – trungduc Apr 01 '18 at 05:58

1 Answers1

1

If you can't use three labels, I think you can use 2 labels to resolve this problem ;).

  • Calculate width and height of text before count down timer. In this case, it's "Price valid for ". You can use below extension to do it.

    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
      }
    }
    
  • Create one more UILabel (countDownLabel) with same font as mainLabel, give it green textColor.
  • Make coundDownLabel overlap mainLabel.
  • Instead of setting

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

    Use

    mainLabel.text = "Price valid for          . All prices are inclusive of 9234% GST.";
    
  • Finally, give countDown a right leading and top constraints.

    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;
    

Result

enter link description here

For more detail, you can take a look at my demo repo here.

trungduc
  • 11,926
  • 4
  • 31
  • 55