0

I am having a problem and have searched all across StackO and did not see a solution.

I have a UITextview extension with TextViewDelegate that I call inside of my VC so that i can have a placeholder label. The problem is i now need to add a func that checks for remaining chars in that same textView which i am able to get to work properly. But i cant grab a label to present it on the VC from that extension. I have been trying delegates but since it is a delegate itself i cant use my normal methods. What is the best route to go about this? Thank You for your help!

Here is the code. The placeholder label code is left out since it will make everything longer and I do not feel its needed for a solution. But I can add if necessary. And i can not move this code straight into VC as i need this extension to stay like this.

extension UITextView: UITextViewDelegate {


/// When the UITextView change, show or hide the label based on if the UITextView is empty or not

public func textViewDidChange(_ textView: UITextView) {
    if let placeholderLabel = self.viewWithTag(100) as? UILabel {
        placeholderLabel.isHidden = !self.text.isEmpty
    }
    checkRemainingChars(textView: textView)

}

func checkRemainingChars(textView: UITextView) {
    let allowedChars = 140
    
    if let charsInTextField = textView.text?.count {
        
        let charsInLabel = charsInTextField
        
        let remainingChars = charsInLabel
        
        if remainingChars <= allowedChars {
            
            //Need to grab this label
           charsLeftLabel.textColor = UIColor.lightGray
        }
        
        if remainingChars >= 120 {
            //Need to grab this label
            charsLeftLabel.textColor = UIColor.orange
            
        }
        
        if remainingChars >= allowedChars {
            //Need to grab this label
            charsLeftLabel.textColor = UIColor.red
        }
        //This prints fine
        print("Remaining chars is \(remainingChars)/140")
        //Need to grab this label
      charsLeftLabel.text = String(remainingChars)
       
    }

}

Thanks again.

aaron
  • 11
  • 4
  • Hi Unfortunately that does not. I am able to add placeholder text inside textview with no issue my problem is how do I access my VC to show UILabel (charsLeftLabel) from my extension as shown in my code. Thanks – aaron Dec 24 '22 at 04:51
  • I misread your issue. It's not about the placeholder, it's about another label you have for showing remaining characters. You would be better off creating a custom view that contains a text view and the needed label. Then it can all be contained in the logic for that custom view class. – HangarRash Dec 24 '22 at 04:55
  • Thanks for getting back to me. Ok that makes sense . What is best route for custom view. a xib file? – aaron Dec 24 '22 at 05:22
  • I see no reason to use a xib. Just write it in code. But that's your choice. – HangarRash Dec 24 '22 at 05:24

0 Answers0