We all know that uitextfield has the placeholder attribute, and uitextview does not have placeholder. How can we simulate uitextfield to make uitextview have placeholder.
The idea is: Inherit the uitextview and make [Super text] display placeholder when the text is null.
The Code is as follows (I referenced arc ):
Uiplaceholdertextview. h
# Import <uikit/uikit. h> @ interface uiplaceholdertextview: uitextview @ property (nonatomic, strong) nsstring * placeholder; // placeholder-(void) addobserver; // Add notification-(void) removeobserver; // remove notification @ end
Uiplaceholdertextview. m
# Import "uiplaceholdertextview. H "@ interface uiplaceholdertextview () @ property (nonatomic, strong) uicolor * textcolor;-(void) beginediting :( nsnotification *) notification;-(void) endediting :( nsnotification *) notification; @ end @ implementation uiplaceholdertextview @ synthesize placeholder; @ synthesize textcolor;-(ID) initwithframe :( cgrect) frame {If (Self = [Super initwithframe: frame]) {[self awakefromnib];} return self;} // this method is called when a nib is created-(void) awakefromnib {textcolor = [uicolor redcolor]; [self addobserver];}-(void) addobserver {[[nsicationcenter center defacenter center] addobserver: Self selector: @ selector (beginediting :) name: uitextviewtextdidbegineditingnotification object: Self]; [[nsicationcenter center defacenter center] addobserver: Self selector: @ selector (endediting :) name: jsonobject: Self];}-(void) removeobserver {[[nsicationicationcenter defacenter center] removeobserver: self] ;}# Pragma mark-# pragma mark setter/getters-(void) setplaceholder :( nsstring *) aplaceholder {placeholder = aplaceholder; [self endediting: Nil];} -(nsstring *) text {nsstring * text = [Super text]; If ([text is1_tostring: placeholder]) return @ ""; return text;}-(void) beginediting :( nsnotification *) Notification {If ([super. text isw.tostring: placeholder]) {super. TEXT = nil; // font color [Super settextcolor: textcolor] ;}}- (void) endediting :( nsnotification *) Notification {If ([super. text isequaltostring: @ ""] | self. TEXT = nil) {super. TEXT = placeholder; // annotation color [Super settextcolor: [uicolor lightgraycolor];}
In viewcontroller, 1. Add a uitextview connection to XIB, 2. directly create an initframe
But don't forget, placeholder, and add and remove notifications.
-(Void) viewdidload {[Super viewdidload]; self. textview. placeholder = @ "Please add your information ...... "; // Do any additional setup after loading the view, typically from a nib .} -(void) viewdidappear :( bool) animated {[Super viewdidappear: Yes]; [self. textview addobserver];}-(void) viewdiddisappear :( bool) animated {[Super viewdiddisappear: Yes]; [self. textview removeobserver];}
:
Thank you for choosing a better method!