UITextView - 水平滚动?

时间:2013-03-03 19:43:25

标签: iphone ios xcode uitextview horizontal-scrolling

如何创建水平滚动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'

1 个答案:

答案 0 :(得分: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];

  6. 希望这会给你一个良好的开端!

    编辑:本准则将有效:

    请注意我使用的是UILabel而不是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];