3

如何创建水平滚动 UITextView?

当我以编程方式设置文本时,它会添加自动换行符,所以我只能垂直滚动......

 titleView.text = @"this is a very long text. this is a very long text. this is a very long text. this is a very long text. this is a very long text.";

感谢您的回答。

编辑:到目前为止我试过这个:

 UIScrollview *yourScrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0 ,0 ,       self.view.frame.size.width, 50)];
CGFloat textLength = [titleView.text sizeWithFont:titleView.font constrainedToSize:CGSizeMake(9999, 50) lineBreakMode:NSLineBreakByWordWrapping].width;

yourScrollview.contentSize = CGSizeMake(textLength + 200, 500); //or some value you like, you may have to try this out a few times

titleView.frame = CGRectMake(titleView.frame.origin.x, titleView.frame.origin.y, textLength, titleView.frame.size.height);

[yourScrollview addSubview: titleView];

NSLog(@"%f", textLength);

但我收到:“威胁 1:信号 SIGABRT”

4

1 回答 1

7

我还没有做过这样的事情,但我会尝试以下步骤来完成这个:

  1. 创建一个UIScrollview *yourScrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0 ,0 , self.view.frame.size.width, 50)]; //

  2. 用于 CGFloat textLength = [titleView.text sizeWithFont:titleView.font constrainedToSize:CGSizeMake(9999, 50) lineBreakMode:NSLineBreakByWordWrapping].width; 获取文本的最终长度

  3. yourScrollView.contentSize = CGSizeMake(textLength + 20, 50); //or some value you like, you may have to try this out a few times

  4. 还设置titleTextView.frame = CGRectMake(titleTextView.frame.origin.x, titleTextView.frame.origin.y, textLength, titleTextView.frame.size.height);

  5. 使 titleView 成为 yourScrollView 的子视图:[yourScrollView addSubview: titleView];

希望这能给你一个好的开始!

编辑:此代码将起作用:

请注意我使用 aUILabel而不是 a UITextView

    UILabel *titleView          = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    titleView.text              = @"this is a very long text. this is a very long text. this is a very long text. this is a very long text. this is a very long text.";
    titleView.font              = [UIFont systemFontOfSize:18];
    titleView.backgroundColor   = [UIColor clearColor];
    titleView.numberOfLines     = 1;

    UIScrollView *myScrollView  = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
    CGFloat textLength          = [titleView.text sizeWithFont:titleView.font constrainedToSize:CGSizeMake(9999, 50) lineBreakMode:NSLineBreakByWordWrapping].width;
    myScrollView.contentSize    = CGSizeMake(textLength + 20, 50); //or some value you like, you may have to try this out a few times

    titleView.frame             = CGRectMake(titleView.frame.origin.x, titleView.frame.origin.y, textLength, titleView.frame.size.height);

    [myScrollView addSubview: titleView];
    [self.view addSubview:myScrollView];
    [titleView release];
    [myScrollView release];
于 2013-03-03T19:59:36.423 回答