限制iOS上的文本输入边界

时间:2015-10-07 12:38:15

标签: ios objective-c uitextfield

我正在为我的公司开发一个应用程序,但我不是obj-C编程语言的专家。我试图在互联网上找到一些答案,但根本没有成功。问题的解决方案可能很简单,但我无法解决。

我想限制文本,使其适合文本框。现在正在发生的事情就是当我开始打字并且它永远在第一行上流动时,当它碰到盒子边界时不会改变到第二行。

    otherdetails = [[UITextField alloc] initWithFrame:otherdetailsf];
    otherdetails.text = otherdetailstxt;
    [otherdetails.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]];
    [otherdetails.layer setBorderWidth:2.0];
    otherdetails.layer.cornerRadius = 5;
    otherdetails.clipsToBounds = YES;
    otherdetails.delegate = self;
    otherdetails.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
    otherdetails.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

当我在文本字段中输入很多内容时会发生什么......

enter image description here

我该如何解决这个问题?

谢谢!

2 个答案:

答案 0 :(得分:1)

如果您需要在文本到达行尾时支持多行文本,请使用TextView而不是文本字段。

来自文档:

  

UITextView类实现了可滚动的行为,   多行文本区域。该类支持使用文本显示   自定义样式信息,还支持文本编辑。你通常   使用文本视图显示多行文本,例如何时   显示大型文本文档的正文。

所以你的代码应该是:

 otherDetails=[[UITextView alloc]initWithFrame:otherdetailsf];
    otherDetails.text=@"";
    [otherDetails.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]];
    [otherDetails.layer setBorderWidth:2.0];
    otherDetails.layer.cornerRadius = 5;
    otherDetails.clipsToBounds = YES;
    otherDetails.delegate = self;

    // otherDetails.contentMode=UIControlContentVerticalAlignmentTop;

答案 1 :(得分:0)

试试这段代码:

在viewcontroller.h中

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextViewDelegate>
@property (strong,nonatomic)IBOutlet UITextView *mytextview;

@end
在viewcontroller.m中

    #import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize mytextview;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)addTextView
{

    [mytextview setText:@"Lorem ipsum dolor sit er elit lamet"];
    mytextview.delegate = self;
     [self.view addSubview:mytextview];

    mytextview.delegate = self;

}

    -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:
    (NSRange)range replacementText:(NSString *)text{
        if ([text isEqualToString:@"\n"]) {
            [textView resignFirstResponder];
        }
        return YES;}

-(void)textViewDidBeginEditing:(UITextView *)textView{
    NSLog(@"Did begin editing");
}
-(void)textViewDidChange:(UITextView *)textView{
    NSLog(@"Did Change");

}
-(void)textViewDidEndEditing:(UITextView *)textView{
    NSLog(@"Did End editing");

}
-(BOOL)textViewShouldEndEditing:(UITextView *)textView{
    [textView resignFirstResponder];
    return YES;
}
@end