6

我有 UIButton,它的标题是动态变化的。按钮大小应随标题大小而变化,并且与标题大小相同。

如何在 Swift 中以编程方式执行此操作?

4

3 回答 3

8

要让您的按钮使用其固有的内容大小并根据其文本自动调整大小,请使用自动布局来定位按钮。仅设置约束来定位按钮,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

如果您在情节提要中创建按钮,这也适用。同样,只给出放置按钮的约束,它将调整大小以适应文本。

于 2018-02-16T12:43:39.703 回答
2

您可以使用UIButton's widthHeight动态获取title.

借助 NSString 的 Size 属性,我们可以实现这一点。

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)")
}

输出

在此处输入图像描述

于 2018-02-16T18:38:52.747 回答
1

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

  1. 创建一个 UILabel (因为 UILabel 调整它的高度和宽度取决于文本)
  2. UIlabel 行数为 1
  3. 在 UILabel 上创建一个 UIButton
  4. 将按钮标题设置为“”
  5. 设置按钮的约束:对齐按钮的顶部并通向 UILabel 并等于宽度和高度

希望这对你有用:)

于 2018-02-16T12:38:47.860 回答