SwiftiOS点点滴滴

Swift 2.0 扩展TextView的placeHolder

2015-12-05  本文已影响629人  xida0325

//

//TextView+Extension.swift

//Tiger

//

//Created by admin on 15/12/5.

//Copyright © 2015年xidaMM. All rights reserved.

//

importFoundation

//MARK:扩展TextView的placeHolder属性

varkPlaceholderLabelPointer:UInt8=0

extension UITextView{

var placeHolderTextView:UITextView? {

get{

return objc_getAssociatedObject(self,&kPlaceholderLabelPointer)as?UITextView

}

set{

objc_setAssociatedObject(self, &kPlaceholderLabelPointer, newValue,objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)

}

}

funcsetPlaceHolder(placeHolderStr:String) {

ifplaceHolderTextView==nil{

placeHolderTextView=UITextView(frame:self.bounds)

placeHolderTextView?.userInteractionEnabled=false

placeHolderTextView?.text= placeHolderStr

placeHolderTextView?.textColor=UIColor.grayColor()

self.insertSubview(placeHolderTextView!, atIndex:0)

}

}

publicoverridefuncwillMoveToSuperview(newSuperview:UIView?) {

NSNotificationCenter.defaultCenter().addObserver(self,

selector:Selector("_didChange:"),

name:UITextViewTextDidChangeNotification,

object:nil)

}

func_didChange (notification:NSNotification) {

guardplaceHolderTextView!=nilelse{

return

}

ifnotification.object===self{

iftext.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) >0{

placeHolderTextView!.hidden=true

}else{

placeHolderTextView!.hidden=false

}

}

}

}

上一篇下一篇

猜你喜欢

热点阅读