我以编程方式创建一个UIButton。我希望对sizeToFit的调用能够用标题大小(和字体)来调整按钮的大小。但它显示了一个嵌入,可以看到上面和下面的标题灰色区域。

所有的嵌入值都显示0.0 (因为它们应该用UIEdgeInsetsZero初始化)
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor lightGrayColor];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:@"Tap Me" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btn.backgroundColor = [UIColor darkGrayColor];
btn.titleLabel.backgroundColor = [UIColor blueColor];
[btn sizeToFit]; // Resize will set the width and height
[self.view addSubview:btn];
NSLog(@"%.2f %.2f %.2f", btn.imageEdgeInsets.top, btn.contentEdgeInsets.top, btn.titleEdgeInsets.top);
// Previous statement output :
// ... Sandbox[1764:59117] 0.00 0.00 0.00
}我肯定我漏掉了什么。在哪里可以找到这些嵌入值?
(这是与iOS 8.3)
基于的sizeToFit更新
一些评论让我更加明确:我知道contentEdgeInsets的默认值是UIEdgeInsetsZero,正如苹果文档中所说的那样。我的帖子建议,不知何故,不同的价值观是适用的。我用两个“空”UIButton控件进行了测试:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.backgroundColor = [UIColor darkGrayColor];
[btn sizeToFit];
[self.view addSubview:btn];
UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeSystem];
btn2.backgroundColor = [UIColor purpleColor];
[btn2 sizeToFit];
[self.view addSubview:btn2];
// Put some code next to move centers to display buttons properly
// ...

sizeToFit后的控制大小为30x34。一些内部逻辑调整了大小,我找不到这个值的来源。它没有反映在contentEdgeInsets中。
发布于 2015-10-12 09:20:17
它是一个bug (21437476),它已经修复:
苹果开发者Relation16-2015-09:51下午我们相信这个问题已经解决了。请验证此问题与iOS 9通用汽车(构建: 13A344),并更新您在http://bugreport.apple.com/的错误报告与结果。 iOS 9通用汽车(构建: 13A344) https://developer.apple.com/ios/download/ 发布日期:9月2015年6月16日
它也在开放雷达上。
发布于 2015-06-17 08:46:57
它在按钮周围增加了一些额外的间距。
尝尝这个
btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
btn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);它会移除插孔。
希望能帮上忙。
发布于 2015-06-17 09:45:08
imageEdgeInsets、contentEdgeInsets、titleEdgeInsets的默认值为UIEdgeInsetsZero。
请使用以下代码:
self.view.backgroundColor = [UIColor lightGrayColor];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:@"Tap Me" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btn.backgroundColor = [UIColor darkGrayColor];
btn.titleLabel.backgroundColor = [UIColor blueColor];
[btn sizeToFit]; // Resize will set the width and height
NSLog(@"%.2f %.2f %.2f", btn.imageEdgeInsets.top, btn.contentEdgeInsets.top, btn.titleEdgeInsets.top);
// Previous statement output :
// ... Sandbox[1764:59117] 0.00 0.00 0.00
btn.contentEdgeInsets = UIEdgeInsetsMake( 10.0, 0.0, 0.0, 0.0);
[self.view addSubview:btn];
NSLog(@"%.2f %.2f %.2f", btn.imageEdgeInsets.top, btn.contentEdgeInsets.top, btn.titleEdgeInsets.top);
// Previous statement output :
// 0.00 10.00 0.00https://stackoverflow.com/questions/30886347
复制相似问题