Why does the UIButton move the title label all the way to the right when I set content insets to move it to the bottom?

StackOverflow https://stackoverflow.com/questions/17158293

  •  01-06-2022
  •  | 
  •  

سؤال

I'm trying to make a UIButton with an image above the text. To that end, I tried setting the edge insets of the button as so:

[button setImageEdgeInsets:UIEdgeInsetsMake(0.0f, 0.0f, 10, 0.0f)];
[button setTitleEdgeInsets:UIEdgeInsetsMake(10, 0.0, 0.0, 0.0)];

What I get is a button where the image is in the same place, and the text is squished all the way over to the side, in a space about one character wide.

How can I simply set the insets so I have the image above the text? Is that really so much to ask?

هل كانت مفيدة؟

المحلول

You just wrongly calculated edgeInSets.They are not there the way you think they are. Here's my test code.It did cost me a while to put image and title in the right place.

UIButton *tmp_testBtn = [[UIButton alloc] initWithFrame:CGRectMake(50, 200, 60, 40)];
tmp_testBtn.backgroundColor = [UIColor grayColor];
[tmp_testBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 20, 0)];
[tmp_testBtn setImage:[UIImage imageNamed:@"France"] forState:UIControlStateNormal];
[tmp_testBtn setTitleEdgeInsets:UIEdgeInsetsMake(20, -258, 0, 0)];
[tmp_testBtn setTitle:@"testbutton" forState:UIControlStateNormal];

CGRect contentRect = [tmp_testBtn contentRectForBounds:tmp_testBtn.bounds];
NSLog(@"contenRect:%f,%f,%f,%f",contentRect.origin.x,contentRect.origin.y,contentRect.size.width,contentRect.size.height);
CGRect titleRect = [tmp_testBtn titleRectForContentRect:contentRect];
NSLog(@"titleRect:%f,%f,%f,%f",titleRect.origin.x,titleRect.origin.y,titleRect.size.width,titleRect.size.height);
CGRect imageRect = [tmp_testBtn imageRectForContentRect:contentRect];
NSLog(@"imageRect:%f,%f,%f,%f",imageRect.origin.x,imageRect.origin.y,imageRect.size.width,imageRect.size.height);

[self.view addSubview:tmp_testBtn];
[tmp_testBtn release];

By the way, I won't do like this.I prefer customize a button with a UIImageView and a UILabel added on.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top