如何根据标题大小设置UIButton的大小?

6
我有一个UIButton,其标题是动态变化的。按钮大小应该随标题大小而变化,并且与标题大小相等。
如何在Swift中以编程方式完成这个操作?
4个回答

9
要使按钮使用其固有内容大小并根据其文本自动调整大小,请使用自动布局来定位按钮。仅设置用于定位按钮的约束条件,iOS将使用文本的大小来确定按钮的宽度和高度。
例如:
let button = UIButton()

// tell it to NOT use the frame
button.translatesAutoresizingMaskIntoConstraints = false

button.setTitle("Hello", for: .normal)
view.addSubview(button)

button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

如果您在Storyboard中创建按钮,同样也可以使用此方法。只需添加约束将按钮放置到指定位置,即可自动调整大小以适应文本。


2

请按照以下步骤操作(这不是一个正式的解决方案,但您可以通过这样做来解决您的问题)

  1. 创建一个UILabel(因为UILabel会根据文本调整其高度和宽度)
  2. 将UIlabel的行数设置为1
  3. 在UILabel上创建一个UIButton
  4. 将按钮标题设置为“”
  5. 设置按钮的约束:将按钮的顶部和前导对齐到UILabel,并等宽等高

希望这对您有所帮助 :)


1
可以,但是如果我想要在按下按钮时为文本获取按下的效果呢?当我设置按钮标题并按下按钮时,我有这样的效果。 - Golovanov Dmytrii

2

通过title属性可以动态获取UIButton的宽度和高度。

利用NSStringSize属性,我们可以实现这一点。

let buttonNAme = [" hi ", "welcome", "Login", "Forgot Password ??", "New to here. Sign up??"]
var yPos = CGFloat()

override func viewWillAppear(_ animated: Bool) {

    yPos = 40

    for i in 0..<buttonNAme.count
    {
        self.view.addSubview(addingCustomButton(buttonTitle: buttonNAme[i], buttonFontSize: 15, buttonCount: i))
    }
}

func addingCustomButton(buttonTitle : String, buttonFontSize: CGFloat, buttonCount : Int) -> UIButton
{
    let ownButton = UIButton()

    ownButton.setTitle(buttonTitle, for: UIControlState.normal)


    ownButton.titleLabel?.font = UIFont.systemFont(ofSize: buttonFontSize)

    let buttonTitleSize = (buttonTitle as NSString).size(attributes: [NSFontAttributeName : UIFont.boldSystemFont(ofSize: buttonFontSize + 1)])

    ownButton.frame.size.height = buttonTitleSize.height * 2
    ownButton.frame.size.width = buttonTitleSize.width
    ownButton.frame.origin.x = 30

    yPos = yPos + (ownButton.frame.size.height) + 10

    ownButton.frame.origin.y = yPos 

    ownButton.tintColor = UIColor.white
    ownButton.backgroundColor = .brown

    ownButton.tag = buttonCount

    ownButton.setTitleColor(UIColor.darkGray, for: UIControlState.highlighted)
    ownButton.addTarget(self, action: #selector(ownButtonAction), for: UIControlEvents.touchUpInside)

    return ownButton
}

func ownButtonAction(sender: UIButton)
{
    print("\n\n Title  \(sender.titleLabel?.text)  TagNum    \(sender.tag)")
}

输出

在此输入图像描述


0

只需约束它的起点,大小就会适合它的按钮标题


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接