Dynamic cell width of UICollectionView depending on label width



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








63















I have a UICollectionView, that loads cells from reusable cell, which contains label. An array provides content for that label. I can resize label width depending on content width easily with sizeToFit. But I cannot make cell to fit label.



Here's the code



- (void)viewDidLoad

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayOfStats = @[@"time:",@"2",@"items:",@"10",@"difficulty:",@"hard",@"category:",@"main"];


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection: (NSInteger)section
return [arrayOfStats count];


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

return CGSizeMake(??????????);


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

return 1;


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

Cell *cell = (Cell *) [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath];
cell.myLabel.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]];
// make label width depend on text width
[cell.myLabel sizeToFit];

//get the width and height of the label (CGSize contains two parameters: width and height)
CGSize labelSize = cell.myLbale.frame.size;

NSLog(@"n width = %f height = %f", labelSize.width,labelSize.height);

return cell;










share|improve this question
























  • similar sort of problem ... stackoverflow.com/questions/24915443/… ???

    – Fattie
    Jul 23 '14 at 16:03

















63















I have a UICollectionView, that loads cells from reusable cell, which contains label. An array provides content for that label. I can resize label width depending on content width easily with sizeToFit. But I cannot make cell to fit label.



Here's the code



- (void)viewDidLoad

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayOfStats = @[@"time:",@"2",@"items:",@"10",@"difficulty:",@"hard",@"category:",@"main"];


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection: (NSInteger)section
return [arrayOfStats count];


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

return CGSizeMake(??????????);


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

return 1;


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

Cell *cell = (Cell *) [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath];
cell.myLabel.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]];
// make label width depend on text width
[cell.myLabel sizeToFit];

//get the width and height of the label (CGSize contains two parameters: width and height)
CGSize labelSize = cell.myLbale.frame.size;

NSLog(@"n width = %f height = %f", labelSize.width,labelSize.height);

return cell;










share|improve this question
























  • similar sort of problem ... stackoverflow.com/questions/24915443/… ???

    – Fattie
    Jul 23 '14 at 16:03













63












63








63


22






I have a UICollectionView, that loads cells from reusable cell, which contains label. An array provides content for that label. I can resize label width depending on content width easily with sizeToFit. But I cannot make cell to fit label.



Here's the code



- (void)viewDidLoad

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayOfStats = @[@"time:",@"2",@"items:",@"10",@"difficulty:",@"hard",@"category:",@"main"];


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection: (NSInteger)section
return [arrayOfStats count];


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

return CGSizeMake(??????????);


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

return 1;


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

Cell *cell = (Cell *) [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath];
cell.myLabel.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]];
// make label width depend on text width
[cell.myLabel sizeToFit];

//get the width and height of the label (CGSize contains two parameters: width and height)
CGSize labelSize = cell.myLbale.frame.size;

NSLog(@"n width = %f height = %f", labelSize.width,labelSize.height);

return cell;










share|improve this question
















I have a UICollectionView, that loads cells from reusable cell, which contains label. An array provides content for that label. I can resize label width depending on content width easily with sizeToFit. But I cannot make cell to fit label.



Here's the code



- (void)viewDidLoad

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayOfStats = @[@"time:",@"2",@"items:",@"10",@"difficulty:",@"hard",@"category:",@"main"];


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection: (NSInteger)section
return [arrayOfStats count];


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

return CGSizeMake(??????????);


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

return 1;


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

Cell *cell = (Cell *) [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath];
cell.myLabel.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]];
// make label width depend on text width
[cell.myLabel sizeToFit];

//get the width and height of the label (CGSize contains two parameters: width and height)
CGSize labelSize = cell.myLbale.frame.size;

NSLog(@"n width = %f height = %f", labelSize.width,labelSize.height);

return cell;







ios objective-c swift uicollectionview uicollectionviewcell






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 11 '18 at 14:30









Hexfire

3,63082034




3,63082034










asked Apr 17 '14 at 13:49









pulppulp

6631819




6631819












  • similar sort of problem ... stackoverflow.com/questions/24915443/… ???

    – Fattie
    Jul 23 '14 at 16:03

















  • similar sort of problem ... stackoverflow.com/questions/24915443/… ???

    – Fattie
    Jul 23 '14 at 16:03
















similar sort of problem ... stackoverflow.com/questions/24915443/… ???

– Fattie
Jul 23 '14 at 16:03





similar sort of problem ... stackoverflow.com/questions/24915443/… ???

– Fattie
Jul 23 '14 at 16:03












7 Answers
7






active

oldest

votes


















69














In sizeForItemAtIndexPath return the size of the text



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

return [(NSString*)[arrayOfStats objectAtIndex:indexPath.row] sizeWithAttributes:NULL];






share|improve this answer


















  • 4





    You cannot imagine how I thank you! That really works. Now I only need to resolve [cell.myLabel sizeToFit] problem, because it appears in its full size only after scrolling. But I have not been even close to your solution.

    – pulp
    Apr 17 '14 at 18:43











  • thank you for your help but I still have one issue. When I uncomment [cell.myLabel sizeToFit] I have words truncated and letters cut at the bottom but it becomes ok after I scroll (words have they normal size and letters jump up a bit). If I comment and disable [cell.myLabel sizeToFit] message (I decided to play around with IB and it works fine) I have words cut at the end and bottom. I made a screenshot goo.gl/HaoqQV It's not very sharp on non-retina displays but you can see that letters have cut. Your suggestion on how to solve will be really appreciated!

    – pulp
    Apr 18 '14 at 7:17






  • 1





    instead of sizeToFit, use sizeWithAttributes to get the CGSize of the text, then set the label's frame with new size.

    – Basheer_CAD
    Apr 18 '14 at 9:13











  • thank you for suggestion but i still have myLabel cut at the bottom and the end. Maybe I'm wrong with implementation of you suggestion. Here's my code

    – pulp
    Apr 18 '14 at 10:30












  • - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath]; cell.myLbale.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]]; CGSize textSize; textSize = [[arrayOfStats objectAtIndex:indexPath.item] sizeWithAttributes:@NSFontAttributeName:[UIFont systemFontOfSize:12.0f]]; [cell.myLbale sizeThatFits:textSize]; //[cell.myLbale sizeToFit]; return cell;

    – pulp
    Apr 18 '14 at 10:32



















26














Checkout below code you might be giving very short CGSize.



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

NSString *testString = @"SOME TEXT";
return [testString sizeWithAttributes:NULL];






share|improve this answer

























  • @Vineesh TP Thank you for your response, I'll definitely check it out and let you know!

    – pulp
    Mar 31 '15 at 17:15











  • +1000 This one definitely works. Yours and Basheer's post should have a green check mark together.

    – rocky raccoon
    Mar 15 '17 at 6:42












  • Any idea how to do this with swift 3?

    – Mobile Bloke
    Apr 8 '17 at 9:32






  • 1





    Thank Man, its Party Time!!

    – Ravi
    Apr 26 '17 at 11:50











  • √ thank you, that the correct answer.

    – Ofir Malachi
    Jul 16 '17 at 11:53


















18














In Swift 3



let size = (arrayOfStats[indexPath.row] as NSString).size(attributes: nil)





share|improve this answer






























    14














    Swift 4.2+



    Principle is:



    1. Implement UICollectionViewDelegateFlowLayout (it contains necessary method signature)


    2. Call collectionView...sizeForItemAt method.


    3. No need to bridge-cast String to NSString to call size(withAttributes: method. Swift String has it out of the box.


    4. Attributes are the same you set for (NS)AttributedString, i.e. font family, size, weight, etc. Optional parameter.



    Sample solution:



    extension ViewController: UICollectionViewDelegateFlowLayout 
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    return "String".size(withAttributes: nil)




    But you would most likely want to specify concrete string attributes respective to your cell, hence final return would look like:



    // Replace "String" with proper string (typically array element). 
    return "String".size(withAttributes: [
    NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14)
    ])





    share|improve this answer
































      9














      Swift 4



      let size = (arrayOfStats[indexPath.row] as NSString).size(withAttributes: nil)





      share|improve this answer






























        8














        I have found a small trick for swift 4.2



        For dynamic width & fixed height:



        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
        let label = UILabel(frame: CGRect.zero)
        label.text = textArray[indexPath.item]
        label.sizeToFit()
        return CGSize(width: label.frame.width, height: 32)



        For dynamic height & fixed width:



        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
        let label = UILabel(frame: CGRect.zero)
        label.text = textArray[indexPath.item]
        label.sizeToFit()
        return CGSize(width: 120, height: label.frame.height)






        share|improve this answer























        • Be careful using this. Creating and drawing a new UILabel for each cell calculation is very expensive.

          – AnthonyR
          Feb 7 at 15:05


















        -1














        //add in view didload



        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        layout.estimatedItemSize = CGSizeMake(self.breadScrumbCollectionView.frame.size.width, 30);
        self.breadScrumbCollectionView.collectionViewLayout = layout;





        share|improve this answer

























          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f23134986%2fdynamic-cell-width-of-uicollectionview-depending-on-label-width%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          69














          In sizeForItemAtIndexPath return the size of the text



          - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

          return [(NSString*)[arrayOfStats objectAtIndex:indexPath.row] sizeWithAttributes:NULL];






          share|improve this answer


















          • 4





            You cannot imagine how I thank you! That really works. Now I only need to resolve [cell.myLabel sizeToFit] problem, because it appears in its full size only after scrolling. But I have not been even close to your solution.

            – pulp
            Apr 17 '14 at 18:43











          • thank you for your help but I still have one issue. When I uncomment [cell.myLabel sizeToFit] I have words truncated and letters cut at the bottom but it becomes ok after I scroll (words have they normal size and letters jump up a bit). If I comment and disable [cell.myLabel sizeToFit] message (I decided to play around with IB and it works fine) I have words cut at the end and bottom. I made a screenshot goo.gl/HaoqQV It's not very sharp on non-retina displays but you can see that letters have cut. Your suggestion on how to solve will be really appreciated!

            – pulp
            Apr 18 '14 at 7:17






          • 1





            instead of sizeToFit, use sizeWithAttributes to get the CGSize of the text, then set the label's frame with new size.

            – Basheer_CAD
            Apr 18 '14 at 9:13











          • thank you for suggestion but i still have myLabel cut at the bottom and the end. Maybe I'm wrong with implementation of you suggestion. Here's my code

            – pulp
            Apr 18 '14 at 10:30












          • - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath]; cell.myLbale.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]]; CGSize textSize; textSize = [[arrayOfStats objectAtIndex:indexPath.item] sizeWithAttributes:@NSFontAttributeName:[UIFont systemFontOfSize:12.0f]]; [cell.myLbale sizeThatFits:textSize]; //[cell.myLbale sizeToFit]; return cell;

            – pulp
            Apr 18 '14 at 10:32
















          69














          In sizeForItemAtIndexPath return the size of the text



          - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

          return [(NSString*)[arrayOfStats objectAtIndex:indexPath.row] sizeWithAttributes:NULL];






          share|improve this answer


















          • 4





            You cannot imagine how I thank you! That really works. Now I only need to resolve [cell.myLabel sizeToFit] problem, because it appears in its full size only after scrolling. But I have not been even close to your solution.

            – pulp
            Apr 17 '14 at 18:43











          • thank you for your help but I still have one issue. When I uncomment [cell.myLabel sizeToFit] I have words truncated and letters cut at the bottom but it becomes ok after I scroll (words have they normal size and letters jump up a bit). If I comment and disable [cell.myLabel sizeToFit] message (I decided to play around with IB and it works fine) I have words cut at the end and bottom. I made a screenshot goo.gl/HaoqQV It's not very sharp on non-retina displays but you can see that letters have cut. Your suggestion on how to solve will be really appreciated!

            – pulp
            Apr 18 '14 at 7:17






          • 1





            instead of sizeToFit, use sizeWithAttributes to get the CGSize of the text, then set the label's frame with new size.

            – Basheer_CAD
            Apr 18 '14 at 9:13











          • thank you for suggestion but i still have myLabel cut at the bottom and the end. Maybe I'm wrong with implementation of you suggestion. Here's my code

            – pulp
            Apr 18 '14 at 10:30












          • - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath]; cell.myLbale.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]]; CGSize textSize; textSize = [[arrayOfStats objectAtIndex:indexPath.item] sizeWithAttributes:@NSFontAttributeName:[UIFont systemFontOfSize:12.0f]]; [cell.myLbale sizeThatFits:textSize]; //[cell.myLbale sizeToFit]; return cell;

            – pulp
            Apr 18 '14 at 10:32














          69












          69








          69







          In sizeForItemAtIndexPath return the size of the text



          - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

          return [(NSString*)[arrayOfStats objectAtIndex:indexPath.row] sizeWithAttributes:NULL];






          share|improve this answer













          In sizeForItemAtIndexPath return the size of the text



          - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

          return [(NSString*)[arrayOfStats objectAtIndex:indexPath.row] sizeWithAttributes:NULL];







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Apr 17 '14 at 14:07









          Basheer_CADBasheer_CAD

          4,3811833




          4,3811833







          • 4





            You cannot imagine how I thank you! That really works. Now I only need to resolve [cell.myLabel sizeToFit] problem, because it appears in its full size only after scrolling. But I have not been even close to your solution.

            – pulp
            Apr 17 '14 at 18:43











          • thank you for your help but I still have one issue. When I uncomment [cell.myLabel sizeToFit] I have words truncated and letters cut at the bottom but it becomes ok after I scroll (words have they normal size and letters jump up a bit). If I comment and disable [cell.myLabel sizeToFit] message (I decided to play around with IB and it works fine) I have words cut at the end and bottom. I made a screenshot goo.gl/HaoqQV It's not very sharp on non-retina displays but you can see that letters have cut. Your suggestion on how to solve will be really appreciated!

            – pulp
            Apr 18 '14 at 7:17






          • 1





            instead of sizeToFit, use sizeWithAttributes to get the CGSize of the text, then set the label's frame with new size.

            – Basheer_CAD
            Apr 18 '14 at 9:13











          • thank you for suggestion but i still have myLabel cut at the bottom and the end. Maybe I'm wrong with implementation of you suggestion. Here's my code

            – pulp
            Apr 18 '14 at 10:30












          • - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath]; cell.myLbale.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]]; CGSize textSize; textSize = [[arrayOfStats objectAtIndex:indexPath.item] sizeWithAttributes:@NSFontAttributeName:[UIFont systemFontOfSize:12.0f]]; [cell.myLbale sizeThatFits:textSize]; //[cell.myLbale sizeToFit]; return cell;

            – pulp
            Apr 18 '14 at 10:32













          • 4





            You cannot imagine how I thank you! That really works. Now I only need to resolve [cell.myLabel sizeToFit] problem, because it appears in its full size only after scrolling. But I have not been even close to your solution.

            – pulp
            Apr 17 '14 at 18:43











          • thank you for your help but I still have one issue. When I uncomment [cell.myLabel sizeToFit] I have words truncated and letters cut at the bottom but it becomes ok after I scroll (words have they normal size and letters jump up a bit). If I comment and disable [cell.myLabel sizeToFit] message (I decided to play around with IB and it works fine) I have words cut at the end and bottom. I made a screenshot goo.gl/HaoqQV It's not very sharp on non-retina displays but you can see that letters have cut. Your suggestion on how to solve will be really appreciated!

            – pulp
            Apr 18 '14 at 7:17






          • 1





            instead of sizeToFit, use sizeWithAttributes to get the CGSize of the text, then set the label's frame with new size.

            – Basheer_CAD
            Apr 18 '14 at 9:13











          • thank you for suggestion but i still have myLabel cut at the bottom and the end. Maybe I'm wrong with implementation of you suggestion. Here's my code

            – pulp
            Apr 18 '14 at 10:30












          • - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath]; cell.myLbale.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]]; CGSize textSize; textSize = [[arrayOfStats objectAtIndex:indexPath.item] sizeWithAttributes:@NSFontAttributeName:[UIFont systemFontOfSize:12.0f]]; [cell.myLbale sizeThatFits:textSize]; //[cell.myLbale sizeToFit]; return cell;

            – pulp
            Apr 18 '14 at 10:32








          4




          4





          You cannot imagine how I thank you! That really works. Now I only need to resolve [cell.myLabel sizeToFit] problem, because it appears in its full size only after scrolling. But I have not been even close to your solution.

          – pulp
          Apr 17 '14 at 18:43





          You cannot imagine how I thank you! That really works. Now I only need to resolve [cell.myLabel sizeToFit] problem, because it appears in its full size only after scrolling. But I have not been even close to your solution.

          – pulp
          Apr 17 '14 at 18:43













          thank you for your help but I still have one issue. When I uncomment [cell.myLabel sizeToFit] I have words truncated and letters cut at the bottom but it becomes ok after I scroll (words have they normal size and letters jump up a bit). If I comment and disable [cell.myLabel sizeToFit] message (I decided to play around with IB and it works fine) I have words cut at the end and bottom. I made a screenshot goo.gl/HaoqQV It's not very sharp on non-retina displays but you can see that letters have cut. Your suggestion on how to solve will be really appreciated!

          – pulp
          Apr 18 '14 at 7:17





          thank you for your help but I still have one issue. When I uncomment [cell.myLabel sizeToFit] I have words truncated and letters cut at the bottom but it becomes ok after I scroll (words have they normal size and letters jump up a bit). If I comment and disable [cell.myLabel sizeToFit] message (I decided to play around with IB and it works fine) I have words cut at the end and bottom. I made a screenshot goo.gl/HaoqQV It's not very sharp on non-retina displays but you can see that letters have cut. Your suggestion on how to solve will be really appreciated!

          – pulp
          Apr 18 '14 at 7:17




          1




          1





          instead of sizeToFit, use sizeWithAttributes to get the CGSize of the text, then set the label's frame with new size.

          – Basheer_CAD
          Apr 18 '14 at 9:13





          instead of sizeToFit, use sizeWithAttributes to get the CGSize of the text, then set the label's frame with new size.

          – Basheer_CAD
          Apr 18 '14 at 9:13













          thank you for suggestion but i still have myLabel cut at the bottom and the end. Maybe I'm wrong with implementation of you suggestion. Here's my code

          – pulp
          Apr 18 '14 at 10:30






          thank you for suggestion but i still have myLabel cut at the bottom and the end. Maybe I'm wrong with implementation of you suggestion. Here's my code

          – pulp
          Apr 18 '14 at 10:30














          - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath]; cell.myLbale.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]]; CGSize textSize; textSize = [[arrayOfStats objectAtIndex:indexPath.item] sizeWithAttributes:@NSFontAttributeName:[UIFont systemFontOfSize:12.0f]]; [cell.myLbale sizeThatFits:textSize]; //[cell.myLbale sizeToFit]; return cell;

          – pulp
          Apr 18 '14 at 10:32






          - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath]; cell.myLbale.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]]; CGSize textSize; textSize = [[arrayOfStats objectAtIndex:indexPath.item] sizeWithAttributes:@NSFontAttributeName:[UIFont systemFontOfSize:12.0f]]; [cell.myLbale sizeThatFits:textSize]; //[cell.myLbale sizeToFit]; return cell;

          – pulp
          Apr 18 '14 at 10:32














          26














          Checkout below code you might be giving very short CGSize.



          - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

          NSString *testString = @"SOME TEXT";
          return [testString sizeWithAttributes:NULL];






          share|improve this answer

























          • @Vineesh TP Thank you for your response, I'll definitely check it out and let you know!

            – pulp
            Mar 31 '15 at 17:15











          • +1000 This one definitely works. Yours and Basheer's post should have a green check mark together.

            – rocky raccoon
            Mar 15 '17 at 6:42












          • Any idea how to do this with swift 3?

            – Mobile Bloke
            Apr 8 '17 at 9:32






          • 1





            Thank Man, its Party Time!!

            – Ravi
            Apr 26 '17 at 11:50











          • √ thank you, that the correct answer.

            – Ofir Malachi
            Jul 16 '17 at 11:53















          26














          Checkout below code you might be giving very short CGSize.



          - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

          NSString *testString = @"SOME TEXT";
          return [testString sizeWithAttributes:NULL];






          share|improve this answer

























          • @Vineesh TP Thank you for your response, I'll definitely check it out and let you know!

            – pulp
            Mar 31 '15 at 17:15











          • +1000 This one definitely works. Yours and Basheer's post should have a green check mark together.

            – rocky raccoon
            Mar 15 '17 at 6:42












          • Any idea how to do this with swift 3?

            – Mobile Bloke
            Apr 8 '17 at 9:32






          • 1





            Thank Man, its Party Time!!

            – Ravi
            Apr 26 '17 at 11:50











          • √ thank you, that the correct answer.

            – Ofir Malachi
            Jul 16 '17 at 11:53













          26












          26








          26







          Checkout below code you might be giving very short CGSize.



          - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

          NSString *testString = @"SOME TEXT";
          return [testString sizeWithAttributes:NULL];






          share|improve this answer















          Checkout below code you might be giving very short CGSize.



          - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

          NSString *testString = @"SOME TEXT";
          return [testString sizeWithAttributes:NULL];







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Sep 10 '18 at 0:56









          Jordan S

          3,1981022




          3,1981022










          answered Feb 25 '15 at 13:09









          Raza.najamRaza.najam

          659613




          659613












          • @Vineesh TP Thank you for your response, I'll definitely check it out and let you know!

            – pulp
            Mar 31 '15 at 17:15











          • +1000 This one definitely works. Yours and Basheer's post should have a green check mark together.

            – rocky raccoon
            Mar 15 '17 at 6:42












          • Any idea how to do this with swift 3?

            – Mobile Bloke
            Apr 8 '17 at 9:32






          • 1





            Thank Man, its Party Time!!

            – Ravi
            Apr 26 '17 at 11:50











          • √ thank you, that the correct answer.

            – Ofir Malachi
            Jul 16 '17 at 11:53

















          • @Vineesh TP Thank you for your response, I'll definitely check it out and let you know!

            – pulp
            Mar 31 '15 at 17:15











          • +1000 This one definitely works. Yours and Basheer's post should have a green check mark together.

            – rocky raccoon
            Mar 15 '17 at 6:42












          • Any idea how to do this with swift 3?

            – Mobile Bloke
            Apr 8 '17 at 9:32






          • 1





            Thank Man, its Party Time!!

            – Ravi
            Apr 26 '17 at 11:50











          • √ thank you, that the correct answer.

            – Ofir Malachi
            Jul 16 '17 at 11:53
















          @Vineesh TP Thank you for your response, I'll definitely check it out and let you know!

          – pulp
          Mar 31 '15 at 17:15





          @Vineesh TP Thank you for your response, I'll definitely check it out and let you know!

          – pulp
          Mar 31 '15 at 17:15













          +1000 This one definitely works. Yours and Basheer's post should have a green check mark together.

          – rocky raccoon
          Mar 15 '17 at 6:42






          +1000 This one definitely works. Yours and Basheer's post should have a green check mark together.

          – rocky raccoon
          Mar 15 '17 at 6:42














          Any idea how to do this with swift 3?

          – Mobile Bloke
          Apr 8 '17 at 9:32





          Any idea how to do this with swift 3?

          – Mobile Bloke
          Apr 8 '17 at 9:32




          1




          1





          Thank Man, its Party Time!!

          – Ravi
          Apr 26 '17 at 11:50





          Thank Man, its Party Time!!

          – Ravi
          Apr 26 '17 at 11:50













          √ thank you, that the correct answer.

          – Ofir Malachi
          Jul 16 '17 at 11:53





          √ thank you, that the correct answer.

          – Ofir Malachi
          Jul 16 '17 at 11:53











          18














          In Swift 3



          let size = (arrayOfStats[indexPath.row] as NSString).size(attributes: nil)





          share|improve this answer



























            18














            In Swift 3



            let size = (arrayOfStats[indexPath.row] as NSString).size(attributes: nil)





            share|improve this answer

























              18












              18








              18







              In Swift 3



              let size = (arrayOfStats[indexPath.row] as NSString).size(attributes: nil)





              share|improve this answer













              In Swift 3



              let size = (arrayOfStats[indexPath.row] as NSString).size(attributes: nil)






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Apr 21 '17 at 14:27









              onyemmemeonyemmeme

              18125




              18125





















                  14














                  Swift 4.2+



                  Principle is:



                  1. Implement UICollectionViewDelegateFlowLayout (it contains necessary method signature)


                  2. Call collectionView...sizeForItemAt method.


                  3. No need to bridge-cast String to NSString to call size(withAttributes: method. Swift String has it out of the box.


                  4. Attributes are the same you set for (NS)AttributedString, i.e. font family, size, weight, etc. Optional parameter.



                  Sample solution:



                  extension ViewController: UICollectionViewDelegateFlowLayout 
                  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
                  return "String".size(withAttributes: nil)




                  But you would most likely want to specify concrete string attributes respective to your cell, hence final return would look like:



                  // Replace "String" with proper string (typically array element). 
                  return "String".size(withAttributes: [
                  NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14)
                  ])





                  share|improve this answer





























                    14














                    Swift 4.2+



                    Principle is:



                    1. Implement UICollectionViewDelegateFlowLayout (it contains necessary method signature)


                    2. Call collectionView...sizeForItemAt method.


                    3. No need to bridge-cast String to NSString to call size(withAttributes: method. Swift String has it out of the box.


                    4. Attributes are the same you set for (NS)AttributedString, i.e. font family, size, weight, etc. Optional parameter.



                    Sample solution:



                    extension ViewController: UICollectionViewDelegateFlowLayout 
                    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
                    return "String".size(withAttributes: nil)




                    But you would most likely want to specify concrete string attributes respective to your cell, hence final return would look like:



                    // Replace "String" with proper string (typically array element). 
                    return "String".size(withAttributes: [
                    NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14)
                    ])





                    share|improve this answer



























                      14












                      14








                      14







                      Swift 4.2+



                      Principle is:



                      1. Implement UICollectionViewDelegateFlowLayout (it contains necessary method signature)


                      2. Call collectionView...sizeForItemAt method.


                      3. No need to bridge-cast String to NSString to call size(withAttributes: method. Swift String has it out of the box.


                      4. Attributes are the same you set for (NS)AttributedString, i.e. font family, size, weight, etc. Optional parameter.



                      Sample solution:



                      extension ViewController: UICollectionViewDelegateFlowLayout 
                      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
                      return "String".size(withAttributes: nil)




                      But you would most likely want to specify concrete string attributes respective to your cell, hence final return would look like:



                      // Replace "String" with proper string (typically array element). 
                      return "String".size(withAttributes: [
                      NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14)
                      ])





                      share|improve this answer















                      Swift 4.2+



                      Principle is:



                      1. Implement UICollectionViewDelegateFlowLayout (it contains necessary method signature)


                      2. Call collectionView...sizeForItemAt method.


                      3. No need to bridge-cast String to NSString to call size(withAttributes: method. Swift String has it out of the box.


                      4. Attributes are the same you set for (NS)AttributedString, i.e. font family, size, weight, etc. Optional parameter.



                      Sample solution:



                      extension ViewController: UICollectionViewDelegateFlowLayout 
                      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
                      return "String".size(withAttributes: nil)




                      But you would most likely want to specify concrete string attributes respective to your cell, hence final return would look like:



                      // Replace "String" with proper string (typically array element). 
                      return "String".size(withAttributes: [
                      NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14)
                      ])






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 15 '18 at 7:12

























                      answered Nov 13 '18 at 15:41









                      HexfireHexfire

                      3,63082034




                      3,63082034





















                          9














                          Swift 4



                          let size = (arrayOfStats[indexPath.row] as NSString).size(withAttributes: nil)





                          share|improve this answer



























                            9














                            Swift 4



                            let size = (arrayOfStats[indexPath.row] as NSString).size(withAttributes: nil)





                            share|improve this answer

























                              9












                              9








                              9







                              Swift 4



                              let size = (arrayOfStats[indexPath.row] as NSString).size(withAttributes: nil)





                              share|improve this answer













                              Swift 4



                              let size = (arrayOfStats[indexPath.row] as NSString).size(withAttributes: nil)






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Aug 15 '18 at 8:37









                              BarathBarath

                              526611




                              526611





















                                  8














                                  I have found a small trick for swift 4.2



                                  For dynamic width & fixed height:



                                  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
                                  let label = UILabel(frame: CGRect.zero)
                                  label.text = textArray[indexPath.item]
                                  label.sizeToFit()
                                  return CGSize(width: label.frame.width, height: 32)



                                  For dynamic height & fixed width:



                                  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
                                  let label = UILabel(frame: CGRect.zero)
                                  label.text = textArray[indexPath.item]
                                  label.sizeToFit()
                                  return CGSize(width: 120, height: label.frame.height)






                                  share|improve this answer























                                  • Be careful using this. Creating and drawing a new UILabel for each cell calculation is very expensive.

                                    – AnthonyR
                                    Feb 7 at 15:05















                                  8














                                  I have found a small trick for swift 4.2



                                  For dynamic width & fixed height:



                                  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
                                  let label = UILabel(frame: CGRect.zero)
                                  label.text = textArray[indexPath.item]
                                  label.sizeToFit()
                                  return CGSize(width: label.frame.width, height: 32)



                                  For dynamic height & fixed width:



                                  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
                                  let label = UILabel(frame: CGRect.zero)
                                  label.text = textArray[indexPath.item]
                                  label.sizeToFit()
                                  return CGSize(width: 120, height: label.frame.height)






                                  share|improve this answer























                                  • Be careful using this. Creating and drawing a new UILabel for each cell calculation is very expensive.

                                    – AnthonyR
                                    Feb 7 at 15:05













                                  8












                                  8








                                  8







                                  I have found a small trick for swift 4.2



                                  For dynamic width & fixed height:



                                  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
                                  let label = UILabel(frame: CGRect.zero)
                                  label.text = textArray[indexPath.item]
                                  label.sizeToFit()
                                  return CGSize(width: label.frame.width, height: 32)



                                  For dynamic height & fixed width:



                                  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
                                  let label = UILabel(frame: CGRect.zero)
                                  label.text = textArray[indexPath.item]
                                  label.sizeToFit()
                                  return CGSize(width: 120, height: label.frame.height)






                                  share|improve this answer













                                  I have found a small trick for swift 4.2



                                  For dynamic width & fixed height:



                                  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
                                  let label = UILabel(frame: CGRect.zero)
                                  label.text = textArray[indexPath.item]
                                  label.sizeToFit()
                                  return CGSize(width: label.frame.width, height: 32)



                                  For dynamic height & fixed width:



                                  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
                                  let label = UILabel(frame: CGRect.zero)
                                  label.text = textArray[indexPath.item]
                                  label.sizeToFit()
                                  return CGSize(width: 120, height: label.frame.height)







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jan 9 at 13:53









                                  Hassan IzharHassan Izhar

                                  8112




                                  8112












                                  • Be careful using this. Creating and drawing a new UILabel for each cell calculation is very expensive.

                                    – AnthonyR
                                    Feb 7 at 15:05

















                                  • Be careful using this. Creating and drawing a new UILabel for each cell calculation is very expensive.

                                    – AnthonyR
                                    Feb 7 at 15:05
















                                  Be careful using this. Creating and drawing a new UILabel for each cell calculation is very expensive.

                                  – AnthonyR
                                  Feb 7 at 15:05





                                  Be careful using this. Creating and drawing a new UILabel for each cell calculation is very expensive.

                                  – AnthonyR
                                  Feb 7 at 15:05











                                  -1














                                  //add in view didload



                                  UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
                                  [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
                                  layout.estimatedItemSize = CGSizeMake(self.breadScrumbCollectionView.frame.size.width, 30);
                                  self.breadScrumbCollectionView.collectionViewLayout = layout;





                                  share|improve this answer





























                                    -1














                                    //add in view didload



                                    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
                                    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
                                    layout.estimatedItemSize = CGSizeMake(self.breadScrumbCollectionView.frame.size.width, 30);
                                    self.breadScrumbCollectionView.collectionViewLayout = layout;





                                    share|improve this answer



























                                      -1












                                      -1








                                      -1







                                      //add in view didload



                                      UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
                                      [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
                                      layout.estimatedItemSize = CGSizeMake(self.breadScrumbCollectionView.frame.size.width, 30);
                                      self.breadScrumbCollectionView.collectionViewLayout = layout;





                                      share|improve this answer















                                      //add in view didload



                                      UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
                                      [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
                                      layout.estimatedItemSize = CGSizeMake(self.breadScrumbCollectionView.frame.size.width, 30);
                                      self.breadScrumbCollectionView.collectionViewLayout = layout;






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Feb 6 '18 at 10:27









                                      Alok Nair

                                      3,34611829




                                      3,34611829










                                      answered Feb 6 '18 at 9:24









                                      Apurva GaikwadApurva Gaikwad

                                      12




                                      12



























                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f23134986%2fdynamic-cell-width-of-uicollectionview-depending-on-label-width%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

                                          Syphilis

                                          Darth Vader #20