美文网首页SwiftiOS点点滴滴
Swift 2.0 扩展TextView的placeHolder

Swift 2.0 扩展TextView的placeHolder

作者: xida0325 | 来源:发表于2015-12-05 14:13 被阅读629次

    //

    //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

    }

    }

    }

    }

    相关文章

      网友评论

        本文标题:Swift 2.0 扩展TextView的placeHolder

        本文链接:https://www.haomeiwen.com/subject/lbgshttx.html