简体   繁体   English

如何左右移动UILabel文本?

[英]How to move UILabel text left or right?

I'm making a calculator and the numbers in the label will always get truncated so the user can't see the full display. 我正在做一个计算器,标签中的数字将始终被截断,因此用户看不到完整的显示。

To fix this problem, I've been told I should make buttons that can move the text in the label left or right on the screen so the user can see the full answer and numbers. 为了解决这个问题,有人告诉我应该做一些按钮,可以在屏幕上左右移动标签中的文本,以便用户可以看到完整的答案和数字。

How would I go about doing this? 我将如何去做呢?

In iOS6 you can use the textAlignment alignment property on UILabel . 在iOS6中,您可以使用UILabel上的textAlignment对齐属性。 You access the label of the UIButton through the property titleLabel . 您可以通过titleLabel属性访问UIButton的标签。 For iOS5 and earlier you can't use attributed strings as easily so it is easier to calculate this yourself. 对于iOS5及更早版本,您无法轻松使用属性字符串,因此您自己计算起来会更容易。

That basically involves looking at the bounds of the view you are placing the text in and figuring out how much space the text will take. 基本上,这涉及查看要放置文本的视图的边界,并弄清楚文本将占用多少空间。 iOS has methods for calculating size of text given a font. iOS具有用于计算给定字体的文本大小的方法。

The code below is an example, which adds a label to a parent view and right alignes this UILabel inside the parent view. 下面的代码是一个示例,该示例将标签添加到parent视图,并在父视图内将该UILabel右对齐。

UILabel * addLabelRightAligned(UIView *parent, NSString *text, UIFont *font)
{
    CGRect frame = {0, 0, 0, 20};
    float padding = 15;                    // give some margins to the text
    CGRect parentBounds = parent.bounds;

    // Figure out how much space the text will consume given a specific font
    CGSize textSize = [text sizeWithFont:font];

    // This is what you are interested in. How we right align the text
    frame.origin.x = parentBounds.size.width - textSize.width - padding;
    frame.origin.y = parentBounds.size.height / 2.0 - textSize.height / 2.0;
    frame.size.width = textSize.width;


    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = text;
    label.font = font;
    label.backgroundColor = [UIColor clearColor];
    [parent addSubview:label];

    return label;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM