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

时间:2018-02-16 12:23:36

标签: swift uibutton cgsize

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

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

3 个答案:

答案 0 :(得分:1)

按照以下步骤(它不是一个合适的解决方案,但你可以通过这样做来解决你的问题)

  1. 创建UILabel(因为UILabel调整其高度和宽度取决于文本)
  2. UIlabel行数为1
  3. 通过UILabel创建UIButton
  4. 将按钮标题设置为""
  5. 设置按钮的约束:对齐按钮顶部并指向UILabel并等于宽度和高度
  6. 希望这对你有用:)

答案 1 :(得分:1)

您可以使用UIButton's动态获取width Heighttitle

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

<强>输出

enter image description here

答案 2 :(得分:0)

要让您的按钮使用其内在内容大小并根据其文本自动调整大小,请使用自动布局来定位按钮。只设置约束来定位按钮,iOS将使用文本的大小来确定按钮的宽度和高度。

例如:

add_action( 'woocommerce_email', 'removing_POS_emails' );
function removing_POS_emails( $email_class, $order_id ) {

     //Remove the Processing email for POS emails
     $pos_test = get_post_meta( $order_id, '_pos', true );
     if ( $pos_test == "1" ) {
         remove_action( 'woocommerce_order_status_pending_to_processing_notification', array( $email_class->emails['WC_Email_Customer_Processing_Order'], 'trigger' ) );
     }
}

如果您在Storyboard中创建按钮,这也有效。同样,只给出放置按钮的约束,它将调整大小以容纳文本。