gpt4 book ai didi

ios - UIButton setImage 有问题

转载 作者:行者123 更新时间:2023-11-28 06:07:36 25 4
gpt4 key购买 nike

enter image description here我正在尝试制作自己的自定义 Facebook 登录按钮。我很接近,但出于某种原因,当我在 UIButton 上设置图像时,它仍然有一个非常大的框架,将文本推到右边,图标也推到右边。

我错过了什么?我尝试设置框架,但没有帮助。(实际图像很大,但 .scaleAspetFit 使它看起来很完美,但我认为框架仍然存在?)

let customFacebookButton: UIButton = {
let view = UIButton()
view.setImage(UIImage(named: "fb-logo"), for: .normal)
view.imageEdgeInsets = UIEdgeInsetsMake(8, 8, 8, 4)
view.imageView?.contentMode = .scaleAspectFit
view.backgroundColor = UIColor.init(hex: "3B5998")
view.layer.cornerRadius = 6
let mutableAttributedString = NSMutableAttributedString()
let attributes: [NSAttributedStringKey: Any] = [
NSAttributedStringKey.font : UIFont.systemFont(ofSize: 14),
NSAttributedStringKey.foregroundColor : UIColor.init(hex: "#EFEFEF") ]
let string = NSMutableAttributedString(string: "Continue with Facebook", attributes: attributes)
mutableAttributedString.append(string)
view.setAttributedTitle(mutableAttributedString, for: .normal)
return view
}()

Custom Facebook UIButton

最佳答案

这是因为图像的大小。缩小图像尺寸。它将完美运行。

我已经用两种图像尺寸 512*512 和 80*80 测试了您的代码。

512*512

/image/zuRWo.png

80*80

/image/YvID9.png

左对齐图像:

  view.contentHorizontalAlignment = .left

无法将标题与左对齐图像居中。您可以暂时更改 titleEdgeInsets 来执行此操作:

  view.titleEdgeInsets = UIEdgeInsetsMake(8, 16, 8, 4)

您可以在按钮左侧放置一个 imageView。并将图像作为按钮的一部分删除。然后居中对齐 contentHorizo​​ntalAlignment。

代码:

  let customFacebookButton: UIButton = {
let view = UIButton()
// view.setImage(UIImage(named: "logo"), for: .normal)
// view.imageEdgeInsets = UIEdgeInsetsMake(8, 8, 8, 4)
view.backgroundColor = UIColor.blue
view.layer.cornerRadius = 6
view.contentHorizontalAlignment = .center
let mutableAttributedString = NSMutableAttributedString()
let attributes: [NSAttributedStringKey: Any] = [
NSAttributedStringKey.font : UIFont.systemFont(ofSize: 14),
NSAttributedStringKey.foregroundColor : UIColor.white ]
let string = NSMutableAttributedString(string: "Continue with Facebook", attributes: attributes)
mutableAttributedString.append(string)
view.setAttributedTitle(mutableAttributedString, for: .normal)
return view
}()
customFacebookButton.frame = CGRect.init(x: 10, y: 20, width: 300, height: 40)
self.view.addSubview(customFacebookButton)

let imageView = UIImageView.init(frame: CGRect.init(x: 12, y: 22, width: 38, height: 38))
imageView.image = #imageLiteral(resourceName: "logo")
self.view.addSubview(imageView)

输出:

enter image description here

关于ios - UIButton setImage 有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47785813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com