objective c - iOS: how to display a long text in a UIScrollView? -
edited
i have uiscrollview, has imageview @ top, under there uilabel, , under want put long text.
i tried put uitextview inside of uiscrollview, uitextview has own scroll bar, need put long text , let uiscrollview scrolling not uitextview.
how can achieve ?
i think way ok trying. in code used uilabel , gave size according string long. , here code
//add scroll full size frame 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 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 bigger frame's width make multiline int width = [self calculatewidthfortext:mytext forheight:30 forfont:myfont]+2; if (width > scroll.frame.size.width) { width = scroll.frame.size.width; //calculate height specific width int height = [self calculateheightfortext:mytext forwidth:scroll.frame.size.width forfont:myfont]+2; //change scroll contentsize scroll.contentsize = cgsizemake(self.view.frame.size.width, mytopimage.frame.size.height + height); //now create 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 smaller width give specific height , 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]; } and here methods calculate string size
- (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; }
Comments
Post a Comment