Label under image in UIButton

后端 未结 30 2012
佛祖请我去吃肉
佛祖请我去吃肉 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:26

    Swift 5 - below method works for me

    func centerVerticallyWithPadding(padding : CGFloat) {
            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: max(0, -(totalHeight - imageViewSize.height)),
                left: 0.0,
                bottom: 0.0,
                right: -titleLabelSize.width
            )
    
            self.titleEdgeInsets = UIEdgeInsets(
                top: (totalHeight - imageViewSize.height),
                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
            )
        }
    

    Make sure your button title is not truncate in storyboard/xib else go for
    Solution 2

    class SVVerticalButton: UIButton {
    
        override func layoutSubviews() {
            super.layoutSubviews()
            let padding : CGFloat = 2.0
            if let imageView = self.imageView {
                imageView.frame.origin.x = (self.bounds.size.width - imageView.frame.size.width) / 2.0
                imageView.frame.origin.y = max(0,(self.bounds.size.height - (imageView.frame.size.height + (titleLabel?.frame.size.height ?? 0.0) + padding)) / 2.0)
            }
            if let titleLabel = self.titleLabel {
                titleLabel.frame.origin.x = 0
                titleLabel.frame.origin.y = self.bounds.size.height - titleLabel.frame.size.height
                titleLabel.frame.size.width = self.bounds.size.width
                titleLabel.textAlignment = .center
            }
        }
    
    }
    

提交回复
热议问题