Skip to content

Instantly share code, notes, and snippets.

@matsuhisa
Last active August 29, 2015 14:12
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save matsuhisa/f8d965bcbccf8320aa17 to your computer and use it in GitHub Desktop.
UITextViewでのPlaceHolder(プレースホルダ)をSwiftで実装する方法 ref: http://qiita.com/matsuhisa@github/items/5f4877e8ec89729de824
import UIKit
public class UIPlaceHolderTextView: UITextView {
lazy var placeHolderLabel:UILabel = UILabel()
var placeHolderColor:UIColor = UIColor.lightGrayColor()
var placeHolder:NSString = ""
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect){
super.init(frame: frame)
}
override init() {
super.init()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override public func awakeFromNib() {
super.awakeFromNib()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChanged:", name: UITextViewTextDidChangeNotification, object: nil)
}
func setText(text:NSString) {
super.text = text
self.textChanged(nil)
}
override public func drawRect(rect: CGRect) {
if(self.placeHolder.length > 0) {
self.placeHolderLabel.frame = CGRectMake(8,8,self.bounds.size.width - 16,0)
self.placeHolderLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
self.placeHolderLabel.numberOfLines = 0
self.placeHolderLabel.font = self.font
self.placeHolderLabel.backgroundColor = UIColor.clearColor()
self.placeHolderLabel.textColor = self.placeHolderColor
self.placeHolderLabel.alpha = 0
self.placeHolderLabel.tag = 999
self.placeHolderLabel.text = self.placeHolder
self.placeHolderLabel.sizeToFit()
self.addSubview(placeHolderLabel)
}
self.sendSubviewToBack(placeHolderLabel)
if(self.text.utf16Count == 0 && self.placeHolder.length > 0){
self.viewWithTag(999)?.alpha = 1
}
super.drawRect(rect)
}
public func textChanged(notification:NSNotification?) -> (Void) {
if(self.placeHolder.length == 0){
return
}
if(countElements(self.text) == 0) {
self.viewWithTag(999)?.alpha = 1
}else{
self.viewWithTag(999)?.alpha = 0
}
}
}
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var TestWebView: UIWebView!
@IBOutlet weak var InputView: UIPlaceHolderTextView!
override func viewDidLoad() {
super.viewDidLoad()
InputView.placeHolder = "本文です。"
InputView.placeHolderColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.5)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment