I wish to align title and image in UiButton in such a manner that the title appears on the left and the image to the extreme right. Please note that the button is stretched so as to fill the screen horizontally.
The button layout should look something like this:- [title .. ]
The title should have some left padding. The image should have some right padding.
CGFloat width = self.frame.size.width;
CGFloat imageWidth = [button currentImage].size.width;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[button setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, width - imageWidth - 10, 0, 0)];
However, though the title is left align, there is a lot of space on it's left. The image does not show up at all!
Following Code will work
UIButton *sectionheader=[[UIButton alloc]initWithFrame:CGRectMake(0,0,320,44)];
[sectionheader setImageEdgeInsets:UIEdgeInsetsMake(0,6,0,0)];
sectionheader.userInteractionEnabled=NO;
[sectionheader setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
// Now Create Label and addsubview to button
UILabel *lblkey=[[UILabel alloc] initWithFrame:CGRectMake(0,0,sectionheader.frame.size.width-10,sectionheader.frame.size.height)];
lblkey.accessibilityValue=@"Value";
lblkey.font=[UIFont fontWithName:themefont size:20];
lblkey.text=[creteria uppercaseString];
lblkey.backgroundColor=[UIColor clearColor];
lblkey.shadowColor = [UIColor blackColor];
lblkey.shadowOffset = CGSizeMake(0, 2);
lblkey.textAlignment=NSTextAlignmentRight;
lblkey.textColor=[UIColor whiteColor];
[sectionheader addSubview:lblkey];
And suppoce you value is going to change always and you want to make it perfect than Make UIButton class and than add above code in that category class than just call following method to change value of that label
+(void)settitle:(NSString *)value:(UIButton *)selfbutton
{
for (UILabel *valuelabel in selfbutton.subviews)
{
if ([valuelabel.accessibilityValue isEqualToString:@"Value"])
{
valuelabel.text=value;
}
}
}

I will go with alternative
What you can do is add three control in one view. lets say ParentView:
1) yourButton
2) yourlable // don't use button title instead use this lable.
3) imageView
now make the ParentView autosize like below:

so as yourButton will stretched horizontally it will automatically resize ParentView.
From here on you just want to take care about position.
set yourlable to extreme left in parentView after yourButton and set autosize property to:
so it will always remain to extreme left of ParentView
And set imageView position to extreme right in parentView and set autosize property to:
so it will always remain to extreme right of ParentView
Hope it will help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With