Swift UIButton左文右图

1,001 阅读1分钟

Swift UIButton左文右图

        //设置button最大宽度 150
        let button = UIButton(frame: CGRect(x: 0, y: 100, width: 150, height: 44))
        button.center = view.center
        let image = UIImage(named: "xxx", in: xxx, compatibleWith: nil)
        button.setImage(image, for: .normal)
        button.imageView?.contentMode = .scaleAspectFit
        // 设置label image动态宽度自适应
        let space: CGFloat = 15
        button?.setTitle("设置label image动态宽度自适应", for: .normal)
        let lableWith = button?.titleLabel?.intrinsicContentSize.width
        let imageWidth = button?.imageView?.intrinsicContentSize.width
        button?.titleEdgeInsets = UIEdgeInsets(top: 0, left: -(imageWidth ?? 0), bottom: 0, right: imageWidth ?? 0)
        button?.imageEdgeInsets = UIEdgeInsets(top: 0, left: (lableWith ?? 0) + space, bottom: 0, right: -((lableWith ?? 0) + space))