【问题标题】:Align image at the right corner of UIButton irrespective of text length与文本长度无关,在 UIButton 的右上角对齐图像
【发布时间】:2023-03-03 21:17:01
【问题描述】:

需要在 UIButton 的右上角对齐图片,与文字长度无关。我设法在文本的右侧设置了一个图像,但它正在放置一个图像,文本结束的地方。下面是我得到的代码和输出。

btnSelect.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
btnSelect.imageEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)

【问题讨论】:

    标签: ios swift uibutton


    【解决方案1】:

    使用UIButtonoverride 方法并管理您的标题和图像框架。

    这里是UIButton 子类。

    class ButtonIconRight: UIButton {
        override func imageRect(forContentRect contentRect:CGRect) -> CGRect {
            var imageFrame = super.imageRect(forContentRect: contentRect)
            imageFrame.origin.x = self.bounds.width - imageFrame.width
            return imageFrame
        }
        
        override func titleRect(forContentRect contentRect:CGRect) -> CGRect {
            var titleFrame = super.titleRect(forContentRect: contentRect)
            if (self.currentImage != nil) {
                titleFrame.origin.x = 0
            }
            return titleFrame
        }
    }
    

    【讨论】:

    • 这个怎么用
    • Opps.. 这是基本的。只需将此类提供给 UIButton 控制器即可。还没搞定?搜索如何使用 UIButton 子类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    相关资源
    最近更新 更多