Uitextfield uitextView自適應高度無標題文章

//設置占位符

text.placeholder=@"Placeholder";

//設置邊框格式

text.borderStyle=UITextBorderStyleRoundedRect;

//設置文字水平位置

text.textAlignment=NSTextAlignmentLeft;

//設置文字垂直位置

text.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;

當彈出的鍵盤遮住了文本框時,可用以下方法來設置適應高度

先注冊2個通知

[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWasShown:)name:UIKeyboardWillShowNotificationobject:nil];

[[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(keyboardDidHide:)name:UIKeyboardWillHideNotificationobject:nil];

好像UIKeyboardWillShowNotification,UIKeyboardWillHideNotification看上去鍵盤和文本框移動位置上比較順暢,

實現2個通知

-(void)keyboardWasShown:(NSNotification*)notification

{

NSDictionary*info=[notification userInfo];

CGSizesize=[[infoobjectForKey:UIKeyboardFrameBeginUserInfoKey]CGRectValue].size;

[UIView beginAnimations:@"skip"context:nil];

[UIView setAnimationDuration:0.1];

CGFloatall=[UIScreenmainScreen].bounds.size.height;

CGFloatoykey=all-size.height;

CGFloatoffset=self.textview.frame.origin.y+self.textview.frame.size.height-oykey;

if(offset>0)

{

self.view.frame=CGRectMake(self.view.frame.origin.x,-offset-10,self.view.frame.size.width,self.view.frame.size.height+offset+10);

UITextView

自適應高度

試了好幾種方法:

一:sizeWithFont:constrainedToSize:lineBreakMode:

CGRectorgRect=self.textView.frame;//獲取原始UITextView的frame

CGSizesize = [self.aModel.zdescription sizeWithFont:[UIFontsystemFontOfSize:12] constrainedToSize:CGSizeMake(280, FLT_MAX)lineBreakMode:NSLineBreakByCharWrapping];

這個方法對于有些能完全顯示,有些會多出一段空白,有些就會截掉一些文字。

不過對于UIlabel 是可以用得。

二:contentSize.height

這個在6之前有用,7就不適用了

orgRect.size.height=self.textView.contentSize.height;//獲取自適應文本內容高度

三:sizeThatFits

能解決自適應高度問題

CGSize myTextViewSize = [self.myTextView sizeThatFits:CGSizeMake(self.myTextView.frame.size.width, FLT_MAX)];

self.myTextView.height = myTextViewSize.height;

NSLog(@"%f", self.myTextView.height);

獲取硬件的輸入鍵盤

- (UIView*)getKeyboardView{

UIView*result =nil;

NSArray*windowsArray = [UIApplicationsharedApplication].windows;

for(UIView*tmpWindowinwindowsArray) {

NSArray*viewArray = [tmpWindowsubviews];

for(UIView*tmpViewinviewArray) {

if([[NSStringstringWithUTF8String:object_getClassName(tmpView)]isEqualToString:@"UIInputSetContainerView"]) {

result = tmpView;

break;

}


}

if(result !=nil) {

break;

}

}

returnresult;

}


如果要做自定義鍵盤,首先獲取系統鍵盤,然后addsubview 將其覆蓋,實現自定義鍵盤

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容