Label under image in UIButton

后端 未结 30 2074
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 15:53

I\'m trying to create a button which has some text beneath the icon (sorta like the app buttons) however it seems to be quite difficult to achieve. Any ideas how can I go ab

30条回答
  •  我在风中等你
    2020-11-29 16:35

    In Xcode, you can simply set the Edge Title Left Inset to negative the width of the image. This will display the label in the center of the image.

    To get the label to display below the image (sorta like the app buttons), you may need to set the Edge Title Top Inset to some positive number.

    Edit: Here is some code to achieve that without using Interface Builder:

    /// This will move the TitleLabel text of a UIButton to below it's Image and Centered.
    /// Note: No point in calling this function before autolayout lays things out.
    /// - Parameter padding: Some extra padding to be applied
    func centerVertically(padding: CGFloat = 18.0) {
        // No point in doing anything if we don't have an imageView size
        guard let imageFrame = imageView?.frame else { return }
        titleLabel?.numberOfLines = 0
        titleEdgeInsets.left = -(imageFrame.width + padding)
        titleEdgeInsets.top = (imageFrame.height + padding)
    }
    

    Please note this won't work if you're using autolayout and the button didn't get layed out in the screen yet via constraints.

提交回复
热议问题