Reputation: 2344
I am attempting to make my own custom Facebook login button. I am close, but for some reason when I setImage on the UIButton it still has a really large frame that is pushing the text to the right and the icon to the right as well.
What am I missing? I tried setting the frame and that did not help. (The actual image is large, but .scaleAspetFit makes it look perfect, but I think the frame persists?)
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
}()
Upvotes: 1
Views: 221
Reputation: 924
It is because of the size of image. Reduce the size of image. It will work perfectly.
I have tested you code with two image sizes 512*512 and 80*80.
512*512
https://i.sstatic.net/zuRWo.png
80*80
https://i.sstatic.net/YvID9.png
for left align the image:
view.contentHorizontalAlignment = .left
There is no way to centre the title with left align image. Temporally you can change titleEdgeInsets to do that:
view.titleEdgeInsets = UIEdgeInsetsMake(8, 16, 8, 4)
OR
You can take a imageView to the left of button. And remove the image as part of button. then centre align the contentHorizontalAlignment.
Code:
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)
Output:
Upvotes: 1