UIButton Text Margin / Padding

后端 未结 9 1145
名媛妹妹
名媛妹妹 2021-01-31 13:39

I have the following layout, and I\'m trying to add a padding to the left and right..

The controls are a disabled UIButton.

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-31 14:00

    The challenge with the accepted answer is that setting the titleEdgeInsets is the limitation, as noted in Apple's documentation:

    This property is used only for positioning the title during layout. The >button does not use this property to determine intrinsicContentSize and >sizeThatFits(_:).

    This means that setting the margins only works if the button is explicitly sized to fit the title label and the margins. If a title is too long or the margins too large, the title text may be clipped. This is OK for a button whose title you know at compile time, but for a variable length button title, can pose a problem.

    An alternate approach accommodating variable title length is to leave the titleEdgeInsets as the default value. Once the button's title is set, add explicit width and height constraints that accommodate the button's title label and the additional margins. For example:

    let margin: CGFloat = 10.0
    
    let button = UIButton()
    
    button.setTitle("My Button Title", for .normal)
    
    button.widthAnchor.constraint(equalToConstant: button.titleLabel!.intrinsicContentSize.width + margin * 2.0).isActive = true
    
    button.heightAnchor.constraint(equalToConstant: button.titleLabel!.intrinsicContentSize.height + margin * 2.0).isActive = true
    

    Position the button without adding further height or width constraints and it will appear properly regardless of title length.

提交回复
热议问题