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
. You access the label of the UIButton
through the property titleLabel
. For iOS5 and earlier you can't use attributed strings as easily so it is easier to calculate this yourself.
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.
The code below is an example, which adds a label to a parent
view and right alignes this UILabel
inside the parent view.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.