ios - 如何创建带有图标下标题和外框的按钮

标签 ios swift uibutton

我想创建带有像this这样的图像的按钮

这是我的代码,但其他型号的 iPhone 则不然:

extension ButtonWithImage {
func alignVertical(spacing: CGFloat = 6.0) {
    guard let imageSize = self.imageView?.image?.size else { return }
    guard let titleSize = titleLabel?.intrinsicContentSize else{return}

    // Title Edge Insets
    let titleEdgeInsets = UIEdgeInsets(top: 0.0 ,
                                       left: -imageSize.width,
                                       bottom: -(self.frame.size.height + 2*spacing),
                                       right: 0.0)
    self.titleEdgeInsets = titleEdgeInsets

    self.imageEdgeInsets = UIEdgeInsets(top: 0.0,
                                        left: 0.0,
                                        bottom: 0.0,
                                        right: -titleSize.width)

    self.contentEdgeInsets = UIEdgeInsets(top: spacing,//edgeOffset,
                                          left: 0.0,
                                          bottom: spacing,//edgeOffset,
                                          right: 0.0)
}
}

titleEdgeInsets 中的底部对于任何型号的 iPhone 都有什么值(value)?

最佳答案

请使用以下扩展程序进行简单使用

extension UIButton {

    func alignCenter(withPadding: CGFloat = 6.0) {
        guard
            let imageViewSize = self.imageView?.frame.size,
            let titleLabelSize = self.titleLabel?.frame.size else {
            return
        }

        let totalHeight = imageViewSize.height + titleLabelSize.height + padding

        self.imageEdgeInsets = UIEdgeInsets(
            top: -(totalHeight - imageViewSize.height),
            left: 0.0,
            bottom: 0.0,
            right: -titleLabelSize.width
        )

        self.titleEdgeInsets = UIEdgeInsets(
            top: 0.0,
            left: -imageViewSize.width,
            bottom: -(totalHeight - titleLabelSize.height),
            right: 0.0
        )

        self.contentEdgeInsets = UIEdgeInsets(
            top: 0.0,
            left: 0.0,
            bottom: titleLabelSize.height,
            right: 0.0
        )
    }

}

关于ios - 如何创建带有图标下标题和外框的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52347962/

相关文章:

ios - 属性文本 boundingRectWithSize 返回错误的大小

swift - 检查字符串中是否有可朗读的字符 - 快速文本到语音

objective-c - 带参数调用 UIAlertView 委托(delegate)方法?

ios - 使用自动布局的 UIButton 动态宽度

ios - 另一个 UIButton 背景颜色问题

iOS11 视觉框架映射所有面部特征点

ios - 将 View Controller 作为参数传递给 AFNetworking 请求是否安全?

iphone - 在 iOS 6.0 中打开 Apple map 并立即开始从当前位置到家的路线

swift - 淡入淡出动画级联 - 有更好的方法吗?

swift - FireStore如何做ClientSideJoin