【问题标题】:UITextView Placeholder did not dissapear after clicked点击后 UITextView 占位符没有消失
【发布时间】:2016-01-29 14:29:42
【问题描述】:

这是我在 xcode 中使用 swift 2 的代码。请先查看。

import UIKit

class sendComplaintViewController: UIViewController, UITextViewDelegate {
    @IBOutlet weak var subjectTextField: UITextField!
    @IBOutlet weak var typeDropDown: IQDropDownTextField!
    @IBOutlet weak var messageTextView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        typeDropDown.isOptionalDropDown = false
        typeDropDown.itemList = ["Choose Category","Complaint", "Suggestion"]
        // Do any additional setup after loading the view.
        messageTextView.text = "Placeholder"
        messageTextView.textColor = UIColor.lightGrayColor()
        
        messageTextView.becomeFirstResponder()
        
        messageTextView.selectedTextRange = messageTextView.textRangeFromPosition(messageTextView.beginningOfDocument, toPosition: messageTextView.beginningOfDocument)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //placeholder textview
    func messageTextView(messageTextView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        // Combine the textView text and the replacement text to
        // create the updated text string
        let currentText:NSString = messageTextView.text
        let updatedText = currentText.stringByReplacingCharactersInRange(range, withString:text)
        
        // If updated text view will be empty, add the placeholder
        // and set the cursor to the beginning of the text view
        if updatedText.isEmpty {
            messageTextView.text = "Placeholder"
            messageTextView.textColor = UIColor.lightGrayColor()
            
            messageTextView.selectedTextRange = messageTextView.textRangeFromPosition(messageTextView.beginningOfDocument, toPosition: messageTextView.beginningOfDocument)
            
            return false
        }
            
            // Else if the text view's placeholder is showing and the
            // length of the replacement string is greater than 0, clear
            // the text view and set its color to black to prepare for
            // the user's entry
        else if messageTextView.textColor == UIColor.lightGrayColor() && !text.isEmpty {
            messageTextView.text = nil
            messageTextView.textColor = UIColor.blackColor()
        }
        
        return true
    }

    func textViewDidChangeSelection(messageTextView: UITextView) {
        if self.view.window != nil {
            if messageTextView.textColor == UIColor.lightGrayColor() {
                messageTextView.selectedTextRange = messageTextView.textRangeFromPosition(messageTextView.beginningOfDocument, toPosition: messageTextView.beginningOfDocument)
            }
        }
    }

    //border textview
    
    override func viewDidLayoutSubviews() {
        // Creates the bottom border
        let borderBottom = CALayer()
        let borderWidth = CGFloat(2.0)
        borderBottom.borderColor = UIColor.grayColor().CGColor
        borderBottom.frame = CGRect(x: 0, y: messageTextView.frame.height - 1.0, width: messageTextView.frame.width , height: messageTextView.frame.height - 1.0)
        borderBottom.borderWidth = borderWidth
        messageTextView.layer.addSublayer(borderBottom)
        messageTextView.layer.masksToBounds = true
        
        // Creates the Top border
        let borderTop = CALayer()
        borderTop.borderColor = UIColor.grayColor().CGColor
        borderTop.frame = CGRect(x: 0, y: 0, width: messageTextView.frame.width, height: 1)
        borderTop.borderWidth = borderWidth
        messageTextView.layer.addSublayer(borderTop)
        messageTextView.layer.masksToBounds = true
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    @IBAction func sendButtonTapped(sender: AnyObject){
        
        //let controltype = controlTypeTextField.selectedItem
        let subject = subjectTextField.text
        let type = typeDropDown.selectedItem
        let complaintMessage = messageTextView.text
        let userId = NSUserDefaults.standardUserDefaults().stringForKey("userId")
       
        if(type == nil || type! == "Choose Category"){
            displayAlertMessage("Please Choose Category")
            return
        }
        if(subject!.isEmpty || type!.isEmpty || complaintMessage!.isEmpty){
            //display an alert message
            displayAlertMessage("All fields are requiered to fill in")
            return
        }
        
        //input fungsi mbprog
        let spinningActivity = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
        spinningActivity.labelText = "Loading"
        spinningActivity.detailsLabelText = "Please wait"
        
        //Send HTTP POST
        
        let myUrl = NSURL(string: "");
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";
        
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
        NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
            
            dispatch_async(dispatch_get_main_queue()){
                
                spinningActivity.hide(true) //waiting send data to server (signup)
                
                if error != nil{
                    self.displayAlertMessage(error!.localizedDescription)
                    return
                }
                
                do {
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
                    
                    if let parseJSON = json {
                        
                        let complaintId = parseJSON["complaintId"] as? String
                        
                        if( complaintId != nil)
                        {
                            let myAlert = UIAlertController(title: "Alert", message: "Success!", preferredStyle: UIAlertControllerStyle.Alert);
                            
                            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){(action) in
                                
                                self.dismissViewControllerAnimated(true, completion: nil)
                            }
                            
                            myAlert.addAction(okAction);
                            self.presentViewController(myAlert, animated: true, completion: nil)
                        } else {
                            let errorMessage = parseJSON["message"] as? String
                            if(errorMessage != nil)
                            {
                                self.displayAlertMessage(errorMessage!)
                            }
                        }
                    }
                } catch{
                    //print(error)
                    print(error)
                    
                    if data != nil {
                        let string = String(data: data!, encoding: NSUTF8StringEncoding)
                        print(string)
                    }
                    
                    print(response)
                }
            }
            
        }).resume()
    }
    
    @IBAction func cancelButtonTapped(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func displayAlertMessage(userMessage:String){
        let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);
        let okAction = UIAlertAction(title: "ok", style: UIAlertActionStyle.Default, handler: nil)
        myAlert.addAction(okAction);
        self.presentViewController(myAlert, animated: true, completion: nil)
    }
}

我的代码中是否有任何错误导致占位符无法正常工作? 占位符已经显示,但点击后并没有消失。 谢谢。

【问题讨论】:

  • 您的问题是发生在messageTextView 还是subjectTextView 上?您是否尝试在它们上写字并且占位符没有消失? ?
  • 问题是 messageTextView 并且有 subjectTextField 而不是 SubjectTextView 谢谢@WilliamKinaan
  • 所以只是为了解决您的问题,尽管您在文本视图上书写,但您有占位符吗?
  • @WilliamKinaan 没错,coe 正在 TextView 中写入占位符,而不是成为背景“占位符”本身
  • 在您的代码中,听起来您没有设置占位符,但您设置了一个名为 "placeholder* 的 text 。您是从界面生成器设置占位符吗?跨度>

标签: ios swift uitextview


【解决方案1】:

您正在设置 TextView 的文本,而不是占位符。

这段代码messageTextView.text = "Placeholder"设置文本不是占位符

如果您的视图是 UITextView,请检查此问题Text View Placeholder Swift

【讨论】:

  • 我认为该行属于 textField,我尝试了代码 messageTextView.placeholder = "myplaceholder",它说“'UITextView' 类型的值没有成员'placeholder'”@WilliamKinaan
  • 消息文本视图不是 ui 文本视图吗? (现在在移动设备上,看不到您的代码)
  • 我会在 20 分钟后检查,别担心
  • 是的,消息 textview 是 UITextView 谢谢@WilliamKinaan 现在代码在 textview 中以灰色显示文本,我不知道如何在单击该 textview 后使其消失
  • 你试着开始打字了吗?如果是,占位符不是消失了吗?
【解决方案2】:

您可以轻松使用 HCExtentionSwift。 You can check GitHub link for that pod here

  • 步骤 1 安装 pod 'HCExtentionSwift'
  • 第 2 步转到身份检查器
  • 第三步插入类名TextViewDesign

现在,在执行 3 个步骤后,您将看到 Attribute Inspector 中的变化 从那里您可以插入 PlaceHolder 值

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 2023-03-10
    • 2011-07-17
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 2010-11-22
    相关资源
    最近更新 更多