Подтвердить что ты не робот

IPhone - настройка ширины UILabel в соответствии с текстом

Как настроить метку Width в соответствии с текстом? Если длина текста мала, я хочу, чтобы ширина метки была маленькой... Если длина текста мала, я хочу, чтобы ширина меток соответствовала этой длине текста. Возможно ли это?

На самом деле у меня есть два UIlabels. Мне нужно разместить их поблизости. Но если текст первого ярлыка слишком мал, будет большой пробел. Я хочу удалить этот пробел.

4b9b3361

Ответ 1

//use this for custom font
CGFloat width =  [label.text sizeWithFont:[UIFont fontWithName:@"ChaparralPro-Bold" size:40 ]].width;

//use this for system font 
CGFloat width =  [label.text sizeWithFont:[UIFont systemFontOfSize:40 ]].width;

label.frame = CGRectMake(point.x, point.y, width,height);

//point.x, point.y -> origin for label;
//height -> your label height; 

Ответ 2

Функция sizeWithFont: устарела в iOS 7.0, поэтому вам нужно использовать sizeWithAttributes: для iOS 7.0+. Также для поддержки более старых версий этот код может быть использован:

    CGFloat width;
    if ([[UIDevice currentDevice].systemVersion floatValue] < 7.0)
    {
        width = [text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:16.0 ]].width;
    }
    else
    {
        width = ceil([text sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:16.0]}].width);
    }

Использование функции ceil() по результату sizeWithAttributes: рекомендуется в документации Apple:

"Этот метод возвращает дробные размеры, чтобы использовать возвращаемые размеры для размеров, вы должны поднять его значение до ближайшего более высокого целого с помощью функции ceil."

sizeWithAttributes

Ответ 3

    // In swift 2.0
    let lblDescription = UILabel(frame: CGRectMake(0, 0, 200, 20))
    lblDescription.numberOfLines = 0
    lblDescription.text = "Sample text to show its whatever may be"
    lblDescription.sizeToFit()

    // Its automatically Adjust the height

Ответ 4

Попробуйте эти параметры,

UIFont *myFont = [UIFont boldSystemFontOfSize:15.0];
// Get the width of a string ...
CGSize size = [@"Some string here" sizeWithFont:myFont];

// Get the width of a string when wrapping within a particular width
NSString *mystring = @"some strings some string some strings...";
CGSize size = [mystring sizeWithFont:myFont
                              forWidth:150.0
                lineBreakMode:UILineBreakModeWordWrap];

Вы также можете попробовать с помощью [label sizeToFit];. Используя этот метод, вы можете установить кадр из двух меток как,

[firstLabel sizeToFit];
[secondLabel sizeToFit];
secondLabel.frame = CGRectMake(CGRectGetMaxX(firstLabel.frame), secondLabel.origin.y, secondLabel.frame.size.width, secondLabel.frame.size.height);

Ответ 5

sizeWithFont constrainedToSize:lineBreakMode: - это оригинальный метод использования. Ниже приведен пример использования ниже:

//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];   

//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;

Ответ 6

просто используйте, если вы используете ограничение в своем представлении или xib или cell

[LBl sizeToFit];

если он не работает, то

dispatch_async(dispatch_get_main_queue(), ^{
[LBl sizeToFit];
});

Ответ 7

Попробуйте следующее:

/* Consider these two labels as the labels that you use, 
and that these labels have been initialized */

UILabel* firstLabel;
UILabel* secondLabel;

CGSize labelSize = [firstLabel.text sizeWithFont:[UIFont systemFontOfSize:12]]; 
//change the font size, or font as per your requirements

CGRect firstLabelRect = firstLabel.frame;

firstLabelRect.size.width = labelSize.width; 
//You will get the width as per the text in label

firstLabel.frame = firstLabelRect;


/* Now, let change the frame for the second label */
CGRect secondLabelRect;

CGFloat x = firstLabelRect.origin.x;
CGFloat y = firstLabelRect.origin.y;

x = x + labelSize.width + 20; //There are some changes here.

secondLabelRect = secondLabel.frame;
secondLabelRect.origin.x = x;
secondLabelRect.origin.y = y; 

secondLabel.frame = secondLabelRect;