Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >XCODE 5+ ..。当第二行添加时,如何阻止TextView中的文本跳到键盘上方?

XCODE 5+ ..。当第二行添加时,如何阻止TextView中的文本跳到键盘上方?
EN

Stack Overflow用户
提问于 2014-10-04 15:24:44
回答 1查看 224关注 0票数 0

相对新手问题:在我的textView中输入的文本位于文本视图区域的顶部,直到文本进入第二行,在第二行,它跳到键盘上方的行,然后在添加新行时向上滚动。但我希望文本保持在文本视图的顶部,直到文本到达键盘上方的线,然后向上滚动。我不知道该怎么做才能解决这个问题。

我花了一些时间搜索,没有找到一个简单的例子。如有任何建议,敬请见谅。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-05 12:54:23

最后,我下载了Apple键盘附件应用程序,并修改了代码,使其与之匹配,现在可以工作了。下面是工作代码--但它并不是优雅代码的一个例子,因为我是一个业余爱好者:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#import "CREWGenericNotesVC.h"

@interface CREWGenericNotesVC ()

@property (nonatomic, weak) IBOutlet UIBarButtonItem *doneButton;
@property (nonatomic, weak) IBOutlet UITextView *textView;
// the height constraint we want to change when the keyboard shows/hides
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraintToAdjust; 

// @property(nonatomic) CGSize contentSize;

@end

@implementation CREWGenericNotesVC

#define VIEW_NAME @"CREWGenericNotesVC" // need the name of the view that calls this
#define VIEW_DESCRIPTION @"Generic notes"
#define RETURN_NC @"NCEmergencyKitsList" // where to return to when complete processing 

- (void)viewDidLoad {

[super viewDidLoad];

//    [_textView addObserver:self forKeyPath:@"contentSize" options:  (NSKeyValueObservingOptionNew) context:NULL];

// load saved notes into textView

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];


self.navigationItem.title = [defaults objectForKey:@"VCtitle"];
self.navigationItem.rightBarButtonItem = self.doneButton;

[self initializeView];

}

// create and load entity and notes
- (void) initializeView
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSString *viewName = [defaults objectForKey:@"VCname"]; // parameter to specify which view is calling notes and
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Notes" inManagedObjectContext:context];

NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(viewName = %@)", VIEW_NAME];
[request setPredicate:pred];

NSError *error = nil;
NSArray * objects = [context executeFetchRequest:request error:&error];

if ([objects count] == 0) { // create new notes instance if not already created
    [self newNotes:viewName]; //  create a new empty note object
} else {
    self.textView.text = [self getNotes:viewName];  //  load existing notes
}
} // end of initializeView

// create a new empty Notes record
- (void) newNotes:(NSString*)viewName
{
NSError *error = nil;
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSManagedObject * newNotes;

newNotes = [NSEntityDescription insertNewObjectForEntityForName:@"Notes" inManagedObjectContext:context];

[newNotes setValue:viewName forKey:@"viewName"];
[newNotes setValue:nil forKey:@"viewNotes"];

if (! [context save:&error])
    NSLog(@"newNotes Couldn't save new data! Error:%@", [error description]); 
} // end of newNotes

// read existing notes
- (NSString*) getNotes:(NSString*)viewName// get stored notes
{
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Notes" inManagedObjectContext:context];

NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(viewName = %@)", viewName];
[request setPredicate:pred];

// Execute Fetch Request
NSManagedObjectContext * matches = nil;
NSError *fetchError = nil;
NSArray *objects = [appDelegate.managedObjectContext executeFetchRequest:request error:&fetchError];
if (fetchError) {
    NSLog(@"getNotes Fetch error:%@", fetchError); 
};

NSString *viewNotes;

if (! [objects count] == 0) {
    matches = objects [0];
    viewNotes = [matches valueForKey : @"viewNotes"];
}
return viewNotes;
} // end of getNotes

- (void)saveNotes:(NSString*)viewName toValue:(NSString*)newNotes // to get stored notes and update them
{
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Notes" inManagedObjectContext:context]; // get notes entity

NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(viewName = %@)", viewName ];
[request setPredicate:pred];

NSManagedObject *matches = nil;
NSError *error = nil;
NSArray * objects = [context executeFetchRequest:request error:&error];

if (![objects count] == 0) {
    matches = objects[0];
}
[matches setValue:newNotes forKey:@"viewNotes"];

if (! [context save:&error]) NSLog(@"newNotes Couldn't save notes! Error:%@", [error description]);
} // end of saveSwitch

// keyboard stuff

- (void)viewDidAppear:(BOOL)animated {

// observe keyboard hide and show notifications to resize the text view appropriately
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillShow:)
                                             name:UIKeyboardWillShowNotification
                                           object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillHide:)
                                             name:UIKeyboardWillHideNotification
                                           object:nil];

// start editing the UITextView (makes the keyboard appear when the application launches)
[self editAction:self];
}

- (void)viewDidDisappear:(BOOL)animated {

[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:UIKeyboardWillChangeFrameNotification
                                              object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:UIKeyboardWillHideNotification
                                              object:nil];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[self adjustSelection:self.textView];
}

#pragma mark - Actions

- (IBAction)doneAction:(id)sender  {

// user tapped the Done button, release first responder on the text view
[self.textView resignFirstResponder];

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSString *viewName = [defaults objectForKey:@"VCname"]; // parameter to specify where to save notes
//    NSString *stringNC = [defaults objectForKey:@"NCname"]; // parameter to specify which navigation controller to return to
[self saveNotes:viewName toValue: self.textView.text]; // save notes

[defaults stringForKey:@"NCname"];
UIViewController *viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:[defaults stringForKey:@"NCname"]]; 
[self presentViewController:viewController animated:YES completion:nil];
}

- (IBAction)editAction:(id)sender {

// user tapped the Edit button, make the text view first responder
[self.textView becomeFirstResponder];
}

#pragma mark - UITextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)aTextView {
}

self.navigationItem.rightBarButtonItem = self.doneButton;

return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)aTextView {

[aTextView resignFirstResponder];

return YES;
}

- (void)adjustSelection:(UITextView *)textView {

// workaround to UITextView bug, text at the very bottom is slightly cropped by the keyboard
if ([textView respondsToSelector:@selector(textContainerInset)]) {
    [textView layoutIfNeeded];
    CGRect caretRect = [textView caretRectForPosition:textView.selectedTextRange.end];
    caretRect.size.height += textView.textContainerInset.bottom;
    [textView scrollRectToVisible:caretRect animated:NO];
}
}

- (void)textViewDidBeginEditing:(UITextView *)textView {

[self adjustSelection:textView];
}

- (void)textViewDidChangeSelection:(UITextView *)textView {

[self adjustSelection:textView];
}


#pragma mark - Responding to keyboard events

- (void)adjustTextViewByKeyboardState:(BOOL)showKeyboard keyboardInfo:(NSDictionary *)info {

/*
 Reduce the size of the text view so that it's not obscured by the keyboard.
 Animate the resize so that it's in sync with the appearance of the keyboard.
 */

// transform the UIViewAnimationCurve to a UIViewAnimationOptions mask
UIViewAnimationCurve animationCurve = [info[UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue];
UIViewAnimationOptions animationOptions = UIViewAnimationOptionBeginFromCurrentState;
if (animationCurve == UIViewAnimationCurveEaseIn) {
    animationOptions |= UIViewAnimationOptionCurveEaseIn;
}
else if (animationCurve == UIViewAnimationCurveEaseInOut) {
    animationOptions |= UIViewAnimationOptionCurveEaseInOut;
}
else if (animationCurve == UIViewAnimationCurveEaseOut) {
    animationOptions |= UIViewAnimationOptionCurveEaseOut;
}
else if (animationCurve == UIViewAnimationCurveLinear) {
    animationOptions |= UIViewAnimationOptionCurveLinear;
}

[self.textView setNeedsUpdateConstraints];

if (showKeyboard) {
    UIDeviceOrientation orientation = self.interfaceOrientation;
    BOOL isPortrait = UIDeviceOrientationIsPortrait(orientation);

    NSValue *keyboardFrameVal = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = [keyboardFrameVal CGRectValue];
    CGFloat height = isPortrait ? keyboardFrame.size.height : keyboardFrame.size.width;

    // adjust the constraint constant to include the keyboard's height
    self.constraintToAdjust.constant += height;
}
else {
    self.constraintToAdjust.constant = 0;
}

NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

[UIView animateWithDuration:animationDuration delay:0 options:animationOptions animations:^{
    [self.view layoutIfNeeded];
} completion:nil];

// now that the frame has changed, move to the selection or point of edit
NSRange selectedRange = self.textView.selectedRange;
[self.textView scrollRangeToVisible:selectedRange];
}

- (void)keyboardWillShow:(NSNotification *)notification {

/*
 Reduce the size of the text view so that it's not obscured by the keyboard.
 Animate the resize so that it's in sync with the appearance of the keyboard.
 */

NSDictionary *userInfo = [notification userInfo];
[self adjustTextViewByKeyboardState:YES keyboardInfo:userInfo];
}

- (void)keyboardWillHide:(NSNotification *)notification {

/*
 Restore the size of the text view (fill self's view).
 Animate the resize so that it's in sync with the disappearance of the keyboard.
 */

NSDictionary *userInfo = [notification userInfo];
[self adjustTextViewByKeyboardState:NO keyboardInfo:userInfo];
}

@end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26198144

复制
相关文章
区间/组合/复合/sql查询
$map['id'] = array(array('gt',3),array('lt',10), 'or') ;得到的查询条件是: ( id > 3) OR ( id < 10)
PM吃瓜
2019/08/12
1.1K0
区间/组合/复合/sql查询
用户窗体编程:实现组合框与文本框联动
在VBE中,插入一个类模块,将其重命名为“CComboboxes”。在该类模块中,输入代码:
fanjy
2023/09/27
6100
用户窗体编程:实现组合框与文本框联动
SQL学习之组合查询(UNION)
1、大多数的SQL查询只包含从一个或多个表中返回数据的单条SELECT语句,但是,SQL也允许执行多个查询(多条SELECT语句),并将结果作为一个查询结果集返回。这些组合查询通常称为并或复合查询。 主要有两种情况需要使用组合查询: (1)在一个查询中从不同的表返回结构数据 (2)对一个执行多个查询,按一个查询返回数据 2、使用UNION 使用UNION很简单,所要做的只是给出每条SELECT语句,然后再每条SELECT语句之间加上UNION关键字,这样所给出的SELECT结果集就能组合成一个结果集并返回。
郑小超.
2018/01/24
1.3K0
SQL学习之组合查询(UNION)
MySQL 组合查询及全文本搜索
使用union的规则:1.两条或两条以上的select语句;2.每个select语句必须包含相同的列,表达式或聚集函数;3.这些列可以以不同的次序出现;4.列的数据必须兼容。
小末快跑
2019/07/03
1.1K0
第14课 组合查询创建组合查询union的使用规则
组合查询很容易理解就是讲多个查询的结果放在一起显示 使用UNION关键字进行查询的组合
desperate633
2018/08/22
9730
表单文本框的使用(一) 选择文本
input和textarea都会在value属性保存自己的内容,可设置和读取文本框的值。在textarea中设置value属性无效
赤蓝紫
2023/03/16
1.7K0
表单文本框的使用(一)  选择文本
使用文本框TextView/EditText的清单
在实际的开发中TextView和EditText是非常基本的控件。这两个控件的使用也是十分简单。而TextView/EditText的功能其实也是非常强大,例如简单的图文就可以使用TextView配合Spannable来实现,以及TextView的drawableTop属性。
阳仔
2019/07/31
9260
使用文本框TextView/EditText的清单
sql中的嵌套查询_sql的多表数据嵌套查询
测试的时候发现取出的是一条数据, 因为测试的时候是一天中的两条数据, 没有不同的日期,所以当日以为是正确的 ,然而第二天写入数据了,要取出数据,却发现没有数据, 返回空的行, 以为都是代码又有问题 了,找了半天都没有 ,仔细看看了存储过程中的代码,发现这样返回的数据的确是空的。
全栈程序员站长
2022/09/22
7.1K0
ExcelVBA-ADO-SQL-003多条件组合查询(模糊查询)
假如现在有一个提交表单,里面是N个查询的条件(工号、姓名、性别、年龄、部门、工资、奖金)用户可以只填写其中的几个条件来进行查询。(也可以不填写条件)
哆哆Excel
2022/10/25
2.8K0
ExcelVBA-ADO-SQL-003多条件组合查询(模糊查询)
java中sql如何嵌套查找_SQL 查询嵌套使用[通俗易懂]
id int primary key auto_increment, — 主键id
全栈程序员站长
2022/09/22
4.3K0
java中sql如何嵌套查找_SQL 查询嵌套使用[通俗易懂]
组合查询
查询项目里面放着一个下拉框,下拉框里面每一项要对应到相应的查询内容这样才查询到内容,就比如说项目这里选到了款号了,查询内容就要写对应的款号内容,就不要写颜色这些。
PHY_68
2020/09/16
8730
组合查询
Power BI中的文本大写/小写自动更改现象
在处理一些英文姓名时,经常会发现,excel表中的大小写和Power BI中的不一样,这篇文章简单说明一下:
陈学谦
2021/12/08
4.3K0
Power BI中的文本大写/小写自动更改现象
SQL语句汇总(三)——聚合函数、分组、子查询及组合查询
分组中也可以加入筛选条件WHERE,不过这里一定要注意的是,执行顺序为:WHERE过滤→分组→聚合函数。牢记!
_DIY
2020/05/29
5.1K0
SQL语句汇总(三)——聚合函数、分组、子查询及组合查询
SecureCRT更改vim中#注释的文本内容颜色
今天在学习redis的时候,发现vim打开redis.conf配置文件的时候,#注释起来的代码是蓝色的,阅读起来很不方便。
上分如喝水
2021/08/16
6.2K0
SecureCRT更改vim中#注释的文本内容颜色
Flutter中的文本输入框组件TextField
1. maxLines 最大输入行。默认为单行输入框,配置此参数后则为多行输入框;
越陌度阡
2021/01/05
5.1K0
Flutter中的文本输入框组件TextField
Flat风格的Qml组合框
基于Qml的ComboBox控件修改而成。 组合框代码 import QtQuick 2.0 import QtQuick.Controls 2.0 import QtGraphicalEffect
Qt君
2019/12/16
1.2K0
python文本框事件_文本框事件
οnfοcus=”if(value==’文本框里的字’) {value=”}” οnblur=”if
全栈程序员站长
2022/11/01
3.3K0
ASP.NET中通过文本框的输入实现"拼音码"动态查询的效果
                  <asp:TextBox ID="TextBox1" runat="server" Style="position: relative" Width="200px"                      AutoPostBack="true" OnTextChanged="TextBox1_Changed"></asp:TextBox>                     <asp:Button ID="Button1" runat="server" Style="left: 400px; position: relative; top: 0px"                         Text="查询" OnClick="Button1_Click" />                     <asp:DropDownList ID="DropDownList1" runat="server"  Style="position: relative" Width="200px"                      CausesValidation="True" DataTextField="课程名称">                     </asp:DropDownList></td>
风柏杨4711
2021/03/15
1.4K0
sql中对嵌套查询的处理原则_sql的多表数据嵌套查询
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/169416.html原文链接:https://javaforall.cn
全栈程序员站长
2022/09/22
5.7K0
点击加载更多

相似问题

添加新项时重复ListView项

34

Android ListView不显示新项。

15

ListView在添加新项时闪烁

21

切换到其他活动android studio时删除ListView项

10

如何将新项添加到ListView的底部,同时从顶部删除旧项?

13
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文