我正在尝试制作自己的自定义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
}()
答案 0 :(得分:1)
这是因为图像的大小。减小图像的大小。它会完美地运作。
我已经测试了两个图像尺寸为512 * 512和80 * 80的代码。
<强> 512 * 512 强>
https://i.stack.imgur.com/zuRWo.png
80 * 80
https://i.stack.imgur.com/YvID9.png
左对齐图像:
view.contentHorizontalAlignment = .left
无法将标题置于左对齐图像的中心位置。暂时你可以改变titleEdgeInsets来做到这一点:
view.titleEdgeInsets = UIEdgeInsetsMake(8, 16, 8, 4)
OR
您可以在按钮左侧拍摄imageView。并删除图像作为按钮的一部分。然后居中对齐contentHorizontalAlignment。
<强>代码:强>
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)
<强>输出:强>