UITextView被点击后占位符未消失

3

这是我的Swift 2版Xcode代码,请先仔细查看。

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 上?你尝试在它们上面写入内容时,占位符没有消失吗? - William Kinaan
所以,只是为了理解你的问题,你在文本视图上写入时仍然有占位符? - William Kinaan
@WilliamKinaan 这是正确的,代码是将占位符写入 TextView 而不是成为背景的“占位符”本身。 - Faisal
这解决了你的问题吗? - William Kinaan
还没有,我不知道在我的代码中要如何添加子层到TextView中。@WilliamKinaan - Faisal
显示剩余5条评论
2个回答

3

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

以下代码 messageTextView.text = "Placeholder" 设置的是文本而不是占位符

如果你的视图是UITextView,那么可以参考这个问题Text View Placeholder Swift


我认为那一行代码属于textField,我尝试了这段代码 messageTextView.placeholder = "myplaceholder" 但它显示“UITextView的值没有成员‘placeholder’” @WilliamKinaan - Faisal
消息文本视图不是UI文本视图吗?(现在在移动设备上,无法查看您的代码) - William Kinaan
我会在20分钟内检查,不用担心。 - William Kinaan
是的,消息文本视图是一个UITextView。 谢谢@WilliamKinaan。 现在代码在文本视图中显示灰色文本,我不知道如何在单击该文本视图后使其消失。 - Faisal
你试过开始输入吗?如果是,占位符是否消失了? - William Kinaan
显示剩余2条评论

0

您可以使用 HCExtentionSwift 来实现这个功能,它非常简单。您可以在 GitHub 上查看该 pod 的链接

  • 步骤 1 安装 pod 'HCExtentionSwift'
  • 步骤 2 转到 Identity Inspector
  • 步骤 3 插入类名 TextViewDesign

现在,在完成了这三个步骤之后,您将会在 Attribute Inspector 中看到变化。从那里,您可以插入 PlaceHolder 值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接