//
// ViewController.m
// 一行显示可滚动的文本
//
// Created by apple on 15-5-8.
// Copyright (c) 2015年 apple. All rights reserved.
// #import "ViewController.h" @interface ViewController () {
UIScrollView *_scrollView;
UITextField *_textField1;
NSInteger _indextext;
}
@end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
_scrollView = [[UIScrollViewalloc]initWithFrame:CGRectMake(,CGRectGetHeight(self.view.bounds)/,CGRectGetWidth(self.view.bounds) - , )];
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.bounces = NO;
_scrollView.layer.borderWidth = ;
[self.view addSubview:_scrollView]; NSMutableAttributedString * attributedStr4 = [[NSMutableAttributedStringalloc]initWithString:@"请输入约会内容"];
[attributedStr4 addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(, attributedStr4.length)];
_textField1 = [[UITextField alloc]initWithFrame:CGRectMake(,,CGRectGetWidth(self.view.bounds) - , )];
_textField1.textAlignment = NSTextAlignmentRight;
_textField1.text = @"";
_textField1.textColor = [UIColor grayColor];
_textField1.font = [UIFont fontWithName:@"Helvetica-Bold" size:];
_textField1.attributedPlaceholder = attributedStr4;
[_textField1 addTarget:self action:@selector(textFieldEditChanged:)forControlEvents:UIControlEventEditingChanged];
[_scrollView addSubview:_textField1];
_scrollView.contentSize = CGSizeMake(CGRectGetWidth(_textField1.bounds),); }
- (void)textFieldEditChanged:(UITextField *)textField
{
if (CGRectGetWidth(_textField1.bounds) >=CGRectGetWidth(self.view.bounds) - ) {
_scrollView.contentSize =CGSizeMake(CGRectGetWidth(_textField1.bounds),);
NSLog(@"%.2f",_scrollView.contentSize.width);
if (_indextext != _textField1.text.length) {
[_textField1 sizeToFit];
[_scrollViewsetContentOffset:CGPointMake(CGRectGetWidth(_textField1.bounds) -CGRectGetWidth(_scrollView.bounds), ) animated:NO];
_indextext = _textField1.text.length;
}
}
else {
_textField1.frame = CGRectMake(, ,CGRectGetWidth(self.view.bounds) - , );
[_scrollView setContentOffset:CGPointMake(, ) animated:NO];
_scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.view.bounds) - ,);
_indextext = _textField1.text.length; }
if (_textField1.text.length > ) {
_textField1.text = [_textField1.text substringToIndex:];
} } @end
补1:我这方法其实很笨,大家有好的方法共享出来,共同进步!
补2:textfield加个状态监听器-限制中文
- (void)viewDidLoad
{
[_textField addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged]; [super viewDidLoad];
} - (void)textFieldEditChanged:(UITextField *)textField
{
NSLog(@"textField text : %@", [textField text]);
}
这样,无论是字母还是中文,都能动态获取
上面的中文限制是有bug的当你一直输入拼音不选择汉子到一定数量汉字联想自动关闭了
修改后链接: