How to set label according to text but i want background color also [closed]

女生的网名这么多〃 提交于 2020-01-07 08:35:37

问题


How to set UILabel according to text but I want backGroundColor also in it, if text is small then it will display background small label with background color black and text and vice-versa.How to do?

In image the black background color came according to the dynamic text. I want black background color till the text India.


回答1:


Try this

NSString *sample = @"...";
CGSize txtSz = [sample sizeWithFont:[UIFont fontWithName: @"Helvetica" size: 16]];
CGRect lblFrame = CGRectMake(10,50, txtSz.width, txtSz.height);
yourLabel.frame = lblFrame;
yourLabel.backgroundColor = [UIColor blackColor];



回答2:


for UILabel to fit all text use sizeToFit

[label sizeToFit];

If you want to have pic background make its size as the label size, take an imageview

imageView.frame = CGRectMake(0, 0, label.frame.size.width, label.frame.size.height);

or if want only background color of the label then use

[label setBackgroundColor:[UIColor blackColor]];



回答3:


Calculate the width of the text and assign it to Label frame width.




回答4:


this is am done in my app you must like did this

    label.text = @"Some text" ;

                        CGSize textSize = [label.text sizeWithFont:label.font];

                        backView.frame=CGRectMake(startPointX, startPointY, textSize.width, 1);

here you must create a new view on back of the label and that name is backview and set the frame of that view and then show it it work perfectly in my app :-)




回答5:


The following code may be help you

        UILabel *biotitlelb = [[UILabel alloc]initWithFrame:CGRectMake(0,0,100,16)];
        [biotitlelb setTextColor:[UIColor whiteColor]];
        [biotitlelb setBackgroundColor:[UIColor blackColor]];
        biotitlelb.textAlignment = UITextAlignmentLeft;
        biotitlelb.font = [UIFont fontWithName:@"ArialMT" size:12]; 
        biotitlelb.text = @"sometext";
        CGSize textSize = [biotitlelb.text sizeWithFont:[UIFont fontWithName:@"ArialMT" size:12]];
        CGFloat strikeWidth = textSize.width;
        [biotitlelb setframe:CGRectMake(0,0,strikeWidth,16)];


来源:https://stackoverflow.com/questions/13248734/how-to-set-label-according-to-text-but-i-want-background-color-also

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!