3

this is my code in xcode with swift 2. please see it first.

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)
    }
}

Is there any error in my code that makes placeholder didn't working right? Placeholder is already showing but it didn't disappear after clicked. thank you.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Faisal
  • 308
  • 4
  • 19
  • is your problem happening with `messageTextView ` or `subjectTextView` ? did you try to write on them and you the place holder didn't disappear? ? – William Kinaan Oct 29 '15 at 12:37
  • the problem is messageTextView and there is subjectTextField not SubjectTextView thank youu @WilliamKinaan – Faisal Oct 29 '15 at 12:42
  • so just to get your problem, you are having the placeholder though you are writing on the text view? – William Kinaan Oct 29 '15 at 12:49
  • @WilliamKinaan that's right, the coe is writing the placeholder in the TextView instead of become background "placeholder" itself – Faisal Oct 29 '15 at 12:55
  • in your code, sounds like you don't set the placeholder, but your set a *text* called "placeholder* . Are you setting the placeholder from interface builder? – William Kinaan Oct 29 '15 at 12:57
  • @WilliamKinaan I see, that's make sense. By the way I write it on the code not from interface builder xcode. – Faisal Oct 29 '15 at 13:01
  • Does that solve ur problem? – William Kinaan Oct 29 '15 at 13:03
  • not yet, I didn't know what to change in my code to adding sublayer in the TextView @WilliamKinaan – Faisal Oct 29 '15 at 13:08
  • I added an answer to your original problem. if you have another problem kindly explain what it is, or post a new question – William Kinaan Oct 29 '15 at 13:14
  • Here's a consolidated placeholder solution that could help in the future: http://stackoverflow.com/questions/27652227/text-view-placeholder-swift/28271069#28271069 – clearlight Jan 31 '17 at 02:24

2 Answers2

3

You are setting the text of your TextView, not the placeholder.

This piece of code messageTextView.text = "Placeholder" sets the text not the placeholder

If your view is a UITextView, then check this question Text View Placeholder Swift

Community
  • 1
  • 1
William Kinaan
  • 28,059
  • 20
  • 85
  • 118
  • i think that line belongs to textField, i tried that code messageTextView.placeholder = "myplaceholder" and it says "value of type 'UITextView' has no member 'placeholder' " @WilliamKinaan – Faisal Oct 29 '15 at 13:17
  • Isnt the message text view an ui text view? (now on mobile, can't see your code) – William Kinaan Oct 29 '15 at 13:21
  • I will check in 20 minutes, don't worry – William Kinaan Oct 29 '15 at 13:23
  • yes it is, message textview is an UITextView thank you @WilliamKinaan right now the code is showing text in greycolor in textview and I don't know how to make it disappear after click that textview – Faisal Oct 29 '15 at 13:39
  • Did u try start typing? If yes didn't the placeholder disappear? – William Kinaan Oct 29 '15 at 13:42
  • @Faisal if it is a text view, please check this qeustion http://stackoverflow.com/questions/27652227/text-view-placeholder-swift – William Kinaan Oct 29 '15 at 13:49
  • alright, i will try that code.. I already upvote your answer, thank you @WilliamKinaan – Faisal Oct 30 '15 at 06:42
0

You can use HCExtentionSwift for that it easy. You can check GitHub link for that pod here

  • Step 1 Install pod 'HCExtentionSwift'
  • Step 2 Go to Identity Inspector
  • Step 3 Insert class name TextViewDesign

Now after doing 3 steps you will see changes in Attribute Inspector From there you can insert PlaceHolder Value