2013-10-04 24 views
15

Ich benutze Autolayout mit UIScrollView, um einige Attribute von einem Objekt zu zeigen. Ich lade diese Informationen dynamisch vom Webservice herunter. Der Scrollview hat eine konstante Breite (weil ich kein vertikales Scroll-Verhalten haben möchte) und seine Subviews respektieren diese Breite mit einer Gruppe von Constraints, aber ich kann die Höhe von UILabel nicht dynamisch erhöhen.Dynamische UILabel Höhe in UIScrollView mit Autolayout

I-Code alles und ich verwende viewDidLoad Selektor Subviews erstellen ...

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    . 
    . 
    . 

    UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectZero]; 
    descriptionLabel.translatesAutoresizingMaskIntoConstraints = NO; 
    descriptionLabel.numberOfLines = 0; 
    descriptionLabel.lineBreakMode = NSLineBreakByWordWrapping; 
    descriptionLabel.opaque = YES; 
    descriptionLabel.backgroundColor = [UIColor clearColor]; 
    descriptionLabel.textColor = [UIColor whiteColor]; 
    descriptionLabel.textAlignment = NSTextAlignmentRight; 
    descriptionLabel.font = [UIFont appetitoMediumItalicFontWithSize:15.0f]; 
    descriptionLabel.text = NSLocalizedStringFromTable(@"APT_DISH_DETAIL_DESCRIPTION", @"DishDetail", @"Etiqueta que contiene la descripción del platillo"); 
    [descriptionLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical]; 
    [self.detailContentScrollView addSubview:descriptionLabel]; 
    self.descriptionLabelS = descriptionLabel; 

    . 
    . 
    . 
} 

können Sie beobachten die self.detailContentScrollView Variable, ist dies ein IBOulet aus View-Controller die Spitze geschaffen.

Dann benutze ich die updateConstraints Wähler ...

- (void)updateConstraints { 
[super updateConstraints]; 
// This dictionary has more variables, ok 
NSDictionary *viewsDict = @{@"dish_description_label": self.descriptionLabelS}; 
. 
. 
. 

[self.descriptionLabelS setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical]; 
[self.detailContentScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[view1][dish_description_label]-[view2][view3][view4]-|" options:0 metrics:nil views:viewsDict]]; 

. 
. 
. 
} 

und schließlich, wenn ich die Web-Service-Infos über empfangen, ich sende sizeToFit ‚s UILabel Selektor und layoutIfNeeded aus dem Scrollview. Aber meine UILabel Größe ändert sich nie mit dem neuen Inhalt. Was mache ich falsch?

Antwort

7

UIScrollView Inhaltsgröße aktualisiert wird dynamisch mit automatischem Layout, vielleicht nur Sie folgenden

- (void) setupScroll 
{ 
    [_scrollView setTranslatesAutoresizingMaskIntoConstraints:NO]; 
    [_contentView setTranslatesAutoresizingMaskIntoConstraints:NO]; 

    [_scrollView addSubview:_contentView]; 

    NSArray *horizontal = [NSLayoutConstraint constraintsWithVisualFormat:@"|[_contentView]|" 
                    options:0 
                    metrics:nil 
                    views:NSDictionaryOfVariableBindings(_contentView)]; 
    NSArray *vertical = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]|" 
                   options:0 
                   metrics:nil 
                    views:NSDictionaryOfVariableBindings(_contentView)]; 

    [_scrollView addConstraints:horizontal]; 
    [_scrollView addConstraints:vertical]; 

    UIView *mainView = self.view; 
    horizontal = [NSLayoutConstraint constraintsWithVisualFormat:@"|[_contentView(==mainView)]|" 
                 options:0 
                 metrics:nil 
                  views:NSDictionaryOfVariableBindings(_contentView, mainView)]; 

    [mainView addConstraints:horizontal]; 
} 

tun muss Wo _contentView Sie ist UILabel und Selbst (Wenn Sie eine komplexere Sicht Hierarchie auf einen Blick Behälter gegeben haben). Ansicht ist die Controlleransicht (oder irgendetwas anderes). Hoffe, das hilft auch: iOS Autolayout with UIScrollview: Why does content view of scroll view not fill the scroll view? ....

Vergessen Sie auch nicht Ihre UILabel preferredMaxLayoutWidth

Beifall zu etablieren!

+0

Diese andere funktionelle Lösung für das Problem war, danke. – specktro

+0

Überprüfen Sie diesen Beitrag für eine vollständige Implementierung: http://arielelkin.github.io/articles/uilabel-plus-uiscrollview-plus-autolayout/ – Eric

+0

@Eric: Link ist down. – testing

1

Ich hatte das gleiche Problem. Es scheint einen Fehler mit Apfel zu geben, so dass mehrzeiliger Text einen Zwei-Durchlauf-Ansatz für die Layout-Korrektur erfordert und alles auf der Eigenschaft preferredMaxLayoutWidth beruht.

Ich landete das Hinzufügen dieser beiden Methoden zum ScrollViewController:

- (void)viewDidLayoutSubviews 
{ 
    [super viewDidLayoutSubviews]; 
    [self performSelectorOnMainThread:@selector(adjustScrollContentSizeOnMainThread) withObject:nil waitUntilDone:NO]; 
} 

- (void)adjustScrollContentSizeOnMainThread 
{ 
    self.myLabel.preferredMaxLayoutWidth = self.myLabel.bounds.size.width; 
} 

ich anhand meiner Lösung zu dieser Antwort: https://stackoverflow.com/a/13616052/2828256

+0

danke eine Tonne ... kämpfte mit ihm für eine sehr lange Zeit ... und du hast mich gerettet. – harshitgupta

+1

Es gibt keinen solchen Fehler, daher ist dieser Ansatz nicht erforderlich. @ D33pN16h7's Antwort funktioniert perfekt. Fügen Sie das Label als Unteransicht des Scrollview hinzu, setzen Sie seine 'numberOfLines' auf 0 oder mehr als 1, und fügen Sie dem Scrollview die folgenden Einschränkungen hinzu:' @ "H: | [label (scrollview)]" 'und' @ "V: | [Label] | "'. – Eric

7

Wenn Sie es mit Blick machen wollen:

  • Fügen Sie eine UIScrollview mit einer Constraint-Höhe> = [gewünschter Mindestwert] hinzu, z 480

  • Fügen Sie dem Scrollview ein UILabel mit einer Höhenbeschränkung> = [minimaler Wert, den Sie wa- chen] hinzu, z.460

wie in den folgenden Bildern:

scrollView constraints label constraints viewController the output will be something like that

, wenn Sie es programmatisch

machen müssen

UIScrollView *scrollView= [UIScrollView new]; 
 
    scrollView.translatesAutoresizingMaskIntoConstraints = NO; 
 
    [self.view addSubview:scrollView]; 
 

 
    UILabel *scrollViewLabel = [[UILabel alloc] init]; 
 
    scrollViewLabel.numberOfLines = 0; 
 
    scrollViewLabel.translatesAutoresizingMaskIntoConstraints = NO; 
 
    [scrollView addSubview:scrollViewLabel]; 
 

 
    scrollViewLabel.text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque ac urna ac ipsum sodales fermentum ornare quis tellus. Integer urna dolor, placerat ut pharetra sit amet, mattis a eros. Maecenas dapibus accumsan felis eget faucibus. Nulla rhoncus gravida neque, sed suscipit ex tempor quis. In sagittis sed enim ut posuere. Donec varius euismod rutrum. Pellentesque mauris sem, mollis id odio eu, maximus interdum elit. Mauris pharetra magna ut tortor lobortis sollicitudin. Cras volutpat porta facilisis. Praesent lacinia mi at volutpat accumsan. Sed eu cursus metus. Donec a convallis nunc. Curabitur tempus accumsan lacus vitae luctus. Sed non quam non leo condimentum congue. Nam dui ipsum, elementum in congue id, mollis ac mauris. Morbi finibus turpis quam, ut venenatis magna malesuada ac. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam erat volutpat. Curabitur nulla mi, aliquam faucibus blandit et, maximus eu libero. Duis semper, est posuere egestas interdum, quam nibh convallis odio, efficitur tempor purus arcu quis justo. Donec euismod feugiat urna in viverra. Sed vel tristique massa. Morbi in consequat sem. Nunc placerat lacus a mauris tempus porttitor. Fusce sed iaculis tortor, nec luctus ligula. Donec euismod metus mauris. Mauris sit amet euismod sapien. Praesent lobortis interdum ligula consequat viverra. Quisque et tortor mattis, congue dolor a, sagittis ligula. Phasellus in lacinia magna. Fusce vel placerat nisi. Maecenas egestas mattis lorem, vel tincidunt mauris eleifend et. In eu pulvinar nibh. Suspendisse ac suscipit orci. Suspendisse at lectus vel purus hendrerit lacinia at posuere sapien. Nunc auctor nisi eget nunc suscipit auctor. Donec fringilla odio lectus, quis porttitor nisl fermentum eget. Nam nunc purus, lobortis id sem porta, accumsan egestas quam. Integer blandit feugiat nunc ac scelerisque. Pellentesque vehicula, massa eget mollis aliquam, felis nulla posuere elit, at gravida elit diam id ligula. Suspendisse pharetra velit sed lacus scelerisque viverra. Maecenas volutpat non metus a interdum. In vitae vestibulum enim. Proin vitae libero non odio finibus pulvinar. In condimentum, sapien ac vehicula lobortis, dolor magna iaculis ex, in consectetur turpis orci eget justo. Suspendisse in lobortis justo, bibendum finibus lorem. Suspendisse ullamcorper diam eu elit sollicitudin, at tempus massa dignissim. In a ante rhoncus, porttitor tortor fermentum, molestie nunc. Phasellus mi dolor, vehicula sed sodales ut, sollicitudin ac ex. Praesent consequat, nunc sed posuere condimentum, risus ex malesuada nulla, sed faucibus velit elit ac risus. Ut venenatis ut nisl in hendrerit."; 
 

 

 
    /*** Auto Layout ***/ 
 

 
    NSDictionary *views = NSDictionaryOfVariableBindings(scrollView, scrollViewLabel); 
 

 
    NSArray *scrollViewLabelConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollViewLabel(scrollView)]" options:0 metrics:nil views:views]; 
 
    [scrollView addConstraints:scrollViewLabelConstraints]; 
 

 
    scrollViewLabelConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollViewLabel]|" options:0 metrics:nil views:views]; 
 
    [scrollView addConstraints:scrollViewLabelConstraints]; 
 

 
    NSArray *scrollViewConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[scrollView]-|" options:0 metrics:nil views:views]; 
 
    [self.view addConstraints:scrollViewConstraints]; 
 

 
    scrollViewConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[scrollView]-|" options:0 metrics:nil views:views]; 
 
    [self.view addConstraints:scrollViewConstraints];

1

Hier ist eine vollständige Umsetzung ist:

/*** Init the scrollview and the label ***/ 

UIScrollView *scrollView= [UIScrollView new]; 
scrollView.translatesAutoresizingMaskIntoConstraints = NO; 
[self.view addSubview:scrollView]; 

UILabel *scrollViewLabel = [[UILabel alloc] init]; 
scrollViewLabel.numberOfLines = 0; 
scrollViewLabel.translatesAutoresizingMaskIntoConstraints = NO; 
[scrollView addSubview:scrollViewLabel]; 

scrollViewLabel.text = @"Bacon ipsum dolor sit amet drumstick meatloaf filet mignon ham t-bone andouille meatball venison cow capicola jerky shankle shoulder ground round. Shank filet mignon pork chop ham hock, short ribs jerky prosciutto tongue porchetta. Biltong kevin strip steak tail jowl jerky boudin drumstick pastrami bresaola. Sirloin tail shoulder salami, hamburger beef doner turducken chuck boudin kielbasa sausage pork loin. Ball tip leberkas fatback, pork chop tail ham ribeye. Bresaola pancetta jerky beef kielbasa frankfurter, corned beef filet mignon ribeye tongue porchetta. Prosciutto short loin sirloin doner brisket jerky swine sausage bresaola chuck. Meatloaf pork chop ribeye bacon jerky turducken, andouille pork belly beef ribs ham hock leberkas. Andouille tri-tip capicola beef t-bone shank tenderloin turducken ball tip salami pork belly shankle. Kielbasa pastrami brisket, kevin spare ribs swine tail beef jerky venison filet mignon. Kevin leberkas ball tip, brisket bresaola chuck meatloaf beef doner drumstick hamburger capicola chicken. Tri-tip biltong drumstick pork prosciutto strip steak pastrami brisket shank hamburger flank tail cow. Pastrami beef ribs ribeye boudin spare ribs pork loin. Meatloaf tail pork belly strip steak doner. T-bone meatball pastrami, pork strip steak salami tail beef boudin leberkas. Venison t-bone fatback, pig brisket pork loin landjaeger turkey tri-tip biltong. Drumstick tri-tip hamburger boudin meatball pork pork chop short ribs chuck doner t-bone bacon frankfurter porchetta beef. Turkey cow meatball andouille pancetta, flank strip steak ham hock. Frankfurter corned beef rump turducken brisket, jerky short loin flank tri-tip ball tip ham hock swine spare ribs."; 


/*** Auto Layout ***/ 

NSDictionary *views = NSDictionaryOfVariableBindings(scrollView, scrollViewLabel); 

NSArray *scrollViewLabelConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollViewLabel(scrollView)]" options:0 metrics:nil views:views]; 
[scrollView addConstraints:scrollViewLabelConstraints]; 

scrollViewLabelConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollViewLabel]|" options:0 metrics:nil views:views]; 
[scrollView addConstraints:scrollViewLabelConstraints]; 

NSArray *scrollViewConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[scrollView]-|" options:0 metrics:nil views:views]; 
[self.view addConstraints:scrollViewConstraints]; 

scrollViewConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[scrollView]-|" options:0 metrics:nil views:views]; 
[self.view addConstraints:scrollViewConstraints]; 

Eine detaillierte Erklärung:

https://arielelkin.github.io/articles/uilabel-plus-uiscrollview-plus-autolayout

Verwandte Themen