0
votes

I have a view which has a label on extreme left, then a button with username and then his comment after the button on the right. What I want to do is to position Label where text of UIButton is ending. In this case, if username is long or short, comment will start without any space between the username button and comment label. I am currently doing hard coded like this, how can I achieve dynamic position of UILabel depending upon size of text of UIButtion?, PfButton is subclass of UIButton Thanks

PfButton *button = [PfButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:name forState:UIControlStateNormal];
[button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[button setContentEdgeInsets:UIEdgeInsetsMake(0, 13, 0, 0)];
[button setObjectId:objId];
[button addTarget:self action:@selector(profilePhotoButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(30, -7, 130, 20)];
[[button titleLabel] setTextAlignment:NSTextAlignmentLeft];
[view addSubview:button];

UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(160, -7, 150, 20)];
[messageLabel setFont:[UIFont systemFontOfSize:15]];
[messageLabel setText:msg];
[messageLabel setTextAlignment:NSTextAlignmentLeft];
[view addSubview:messageLabel];
[messageLabel release];
2
the button's titleLabel is a UIView subclass. You can get its frame. Use that to position your other label.KDaker
I am setting a hardcoded frame, how can I resize it so that it covers only the text on the button?kashif789us

2 Answers

1
votes

sizeToFit doesn't work well if you want to have your button be wider than the label, or if you change one of the many sizing properties on the button. A better solution is to simply translate the titleLabel's coordinate system to the buttons superview.

CGRect buttonTitleFrame = button.titleLabel.frame;
CGRect convertedRect = [button convertRect:button.titleLabel.frame toView:button.superview];
CGFloat xForLabel = convertedRect.origin.x + buttonTitleFrame.size.width;
CGRect currentLabelFrame = label.frame;
CGRect labelFrame = CGRectMake(xForLabel, currentLabelFrame.origin.y, currentLabelFrame.size.width, currentLabelFrame.size.height);
label.frame = labelFrame;

The second line is the key one here. You ask the button to convert a rectangle that is within it (in this case the title labels) to what it would be in another view (in this case the buttons superview, which is probably your view controllers self.view).

Line 3 takes the translated origin and adds the labels exact width, and 5 uses the values from the labels frame except the x, which is our calculated value.

0
votes

Got it to work by using

[button sizeToFit];

It gave me the exact frame, then calculated the position of label by taking into account button's x position and width