独立于内容的UIButton的设置大小

独立于内容的UIButton的设置大小

问题描述:

我创建了一系列具有边框的UIButton,其标题将设置为不同的数字。实际上,这些按钮都根据文本的长度来调整自己的大小,但我希望它们的大小相同,比容纳文本所需的大一些,因为这样看起来会更好。独立于内容的UIButton的设置大小

我添加边框使用一个子类的按钮中,我指定以下内容:

self.layer.cornerRadius = 5.0; 
self.layer.borderColor = UIColor.blackColor().CGColor 
self.layer.borderWidth = 1 
self.backgroundColor = UIColor.whiteColor() 
self.tintColor = UIColor.blackColor() 

有没有我可以在绝对数量指定定义按钮四周的边框的矩形的大小的方法吗?我已经尝试将self.frame设置为CGRect,但这似乎不会影响边框。

+0

self.frame = CGRectMake(0.0,0.0,40,40)或尝试使用自动布局 –

+0

在顶部@erkamKUCET答案,不忘记它将此对象添加到SubView – Lamar

你在使用故事板吗?

如果是这样ctrl并将你的按钮拖动到另一个按钮,你想等宽。

如果你不使用故事板:

constraint = [NSLayoutConstraint 
    constraintWithItem:myButton 
     attribute:NSLayoutAttributeWidth 
     relatedBy:NSLayoutRelationEqual 
      toItem: otherButton 
     attribute:NSLayoutAttributeWidth 
     multiplier:1.0f 
     constant:0]; 

让我知道如果您有任何麻烦

+0

谢谢!将按钮设置为相等宽度后,我意识到我可以对宽度设置一个约束。比我最初想象的要复杂得多 –

尝试titleEdgeInsets的UIButton的财产。文档在这里给出:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIButton_Class/#//apple_ref/occ/instp/UIButton/titleEdgeInsets

默认值是零,这意味着它会正好契合