iOS: 如何在UIScrollView 中显示长文本?

iOS: how to display a long text in a UIScrollView?

已编辑

我有一个 UIScrollView,上面有一个 ImageView,下面有一个 UIlabel,下面我想放一个长文本。

我试着把 UITextView 放在 UIScrollView 里面,但是 UITextView 有自己的滚动条,我需要放一个长文本让 UIScrollView 滚动而不是 UITextView.

我怎样才能做到这一点?

我认为这种方式可以做你正在尝试的事情。在我的代码中,我使用了 UILabel 并根据 String[ 给了它一个大小=21=]长。 这是我的代码

//Add an scroll to full size frame to view
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//some properties of scroll
scroll.userInteractionEnabled = YES;
scroll.showsHorizontalScrollIndicator = YES;
[self.view addSubview:scroll];
//now add views into the scroll
UIImageView *myTopImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, scroll.frame.size.width, 100)];
myTopImage.image = [UIImage imageNamed:@"your_image.png"];
UIFont *myFont = [UIFont fontWithName:@"Helvetica Neue" size:30];
[scroll addSubview:myTopImage];

NSString *myText = @"your  long text here";
//calculate width if it bigger than frame's width make it multiline
int width = [self calculateWidthForText:myText forHeight:30 forFont:myFont]+2;
if (width > scroll.frame.size.width) {
    width = scroll.frame.size.width;
    //calculate height for specific width
    int height = [self calculateHeightForText:myText forWidth:scroll.frame.size.width forFont:myFont]+2;
    //change your scroll contentSize
    scroll.contentSize = CGSizeMake(self.view.frame.size.width, myTopImage.frame.size.height + height);

    //now create your label
    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, width, height)];
    myLabel.numberOfLines = 0;
    myLabel.text = myText;
    myLabel.textAlignment = NSTextAlignmentLeft;
    myLabel.font = myFont;
    [scroll addSubview:myLabel];

}else {

    //if it is smaller than width give it specific height and init
    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, width, 30)];
    myLabel.numberOfLines = 0;
    myLabel.text = myText;
    myLabel.textAlignment = NSTextAlignmentLeft;
    myLabel.font = myFont;
    [scroll addSubview:myLabel];

}

这是我计算字符串大小的方法

- (CGFloat) calculateHeightForText:(NSString *)str forWidth:(CGFloat)width forFont:(UIFont *)font {
CGFloat result = 20.0f;
    if (str) {
        CGSize textSize = { width, 20000.0f };
        CGSize size = [str sizeWithFont:font constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];
        result = MAX(size.height, 20.0f);
    }
    return result;
}

- (CGFloat) calculateWidthForText:(NSString *)str forHeight:(CGFloat)height forFont:(UIFont *)font {
CGFloat result = 20.0f;
    if (str) {
        CGSize textSize = { 20000.0f, height };
        CGSize size = [str sizeWithFont:font constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];
        result = MAX(size.width, 20.0f);
    }
    return result;
}