Ios 左对齐图像和UIButton上的中心文本

Ios 左对齐图像和UIButton上的中心文本,ios,uiimage,uibutton,Ios,Uiimage,Uibutton,我看过关于右对齐的帖子,但我无法让左对齐发挥作用。我希望按钮占据屏幕的宽度,图像在左边,标题/文本在中间 这不起作用(至少可靠): 最好创建一个自定义UIButton子类,以更好的方式解决这个问题。苹果可能正在“重置”你的设置。1)button.frame=self.view.bounds 2) setImageEdgeInsets当您的按钮填满屏幕时,使用负值是疯狂的。重新考虑你想在这里做什么 3) UITextAlignmentCenter现在是NSTextAlignmentCenter 4

我看过关于右对齐的帖子,但我无法让左对齐发挥作用。我希望按钮占据屏幕的宽度,图像在左边,标题/文本在中间

这不起作用(至少可靠):


最好创建一个自定义UIButton子类,以更好的方式解决这个问题。苹果可能正在“重置”你的设置。

1)
button.frame=self.view.bounds

2)
setImageEdgeInsets
当您的按钮填满屏幕时,使用负值是疯狂的。重新考虑你想在这里做什么

3)
UITextAlignmentCenter
现在是
NSTextAlignmentCenter


4)
button.contentHorizontalAlignment=uicontrolContentHorizontalAlignment左

在我的最后,我使用UIEdgeInsetsMake完成了这项工作,它的左角被计算到中心。我不确定是否有什么东西可以让文本在中心对齐,但这对我来说很有用。确保通过计算宽度将左角设置到所需位置。e、 g.
UIEdgeInsetsMake(0.0f、42.0f、0.0f、0.0f)

输出看起来像

在Swift中:

var scanBarCodeButton: UIButton = UIButton(type: .roundedRect)
scanBarCodeButton.frame = CGRectMake(center, 10.0, fieldWidth, 40.0)
scanBarCodeButton.setImage(UIImage(named: "BarCodeIcon.png"), for: UIControlStateNormal)
scanBarCodeButton.setTitle("Scan the Barcode", for: UIControlStateNormal)
scanBarCodeButton.titleEdgeInsets = UIEdgeInsetsMake(0.0, 42.0, 0.0, 0.0)
scanBarCodeButton.contentHorizontalAlignment = .left
scanBarCodeButton.addTarget(self, action: "scanBarCode:", for: UIControlEventTouchUpInside)
self.view.addSubview(scanBarCodeButton)

创建按钮并将文本对齐设置为居中,然后添加:

UIImage *image = [UIImage imageNamed:@"..."];
CGSize imageSize = image.size;
CGFloat offsetY = floor((self.layer.bounds.size.height - imageSize.height) / 2.0);

CALayer *imageLayer = [CALayer layer];
imageLayer.contents = (__bridge id) image.CGImage;
imageLayer.contentsGravity = kCAGravityBottom;
imageLayer.contentsScale = [UIScreen mainScreen].scale;
imageLayer.frame = CGRectMake(offsetY, offsetY, imageSize.width, imageSize.height);
[self.layer addSublayer:imageLayer];

我认为,好的解决方案必须对任何文本都有用,而不需要硬编码插入值(这是关于toytoy提供的解决方案)。我使用的代码与此类似:

NSString *sometitle = @"blabla button title";
NSString *someimage = @"blablaimage";
UIImage *image = [[UIImage imageNamed:someimage];
int buttonWidth = A;
int buttonHeight = B;
int imageWidth =image.size.width;
int imageHeight = image.size.height;
int titleWidth = buttonWidth - imageWidth;

// create button and set image and title
buttonView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, buttonWidth, buttonHeight)];
[buttonView setImage:image forState:UIControlStateNormal];
[buttonView setTitle:sometitle forState:UIControlStateNormal];

// make button all content to be left aligned
[buttonView setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];

// set title font 
[buttonView.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:14]];

// calculate font text width with selected font
CGSize stringBoundingBox = [number sizeWithFont:[buttonView.titleLabel font]];

// make title inset with some value from left 
// it place the title right on the center of space for the title
int titleLeft = (titleWidth - stringBoundingBox.width) / 2;
[buttonView setTitleEdgeInsets:UIEdgeInsetsMake(0, titleLeft, 0, 0)];
在stringBoundingBox init的字符串之后,我还添加了如下字符串:

if (stringBoundingBox.width > titleWidth)
{
    [_backgroundView.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:13]];
    stringBoundingBox = [number sizeWithFont:[_backgroundView.titleLabel font]];
}
if (stringBoundingBox.width > titleWidth)
{
    [_backgroundView.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:12]];
    stringBoundingBox = [number sizeWithFont:[_backgroundView.titleLabel font]];
}
它允许我通过选择一些较小的字体来设置比可用空间更长的标题。我这样做是因为另一种方式:

[buttonView.titleLabel setAdjustsFontSizeToFitWidth:YES];
工程不是很好,看起来它采取的字体大小为3-4点小了一步,所以一些不太长的线变得太小,比它必须要小


这段代码允许我们将按钮标题空间中的任何文本精确地放在中间。

我在这里看到很多解决方案,它们都侧重于将图标设置到左侧。我认为只需添加UIImageView,将按钮的左侧与图像对齐,并将它们放在一起居中,就更容易了。然后你可以玩一点偏移,使它看起来很漂亮


无代码,全部在Interface Builder中。

这对我来说很好,适用于几个按钮,具有不同的图像宽度和不同的标题长度:

子类
ui按钮
,并添加以下方法:

override func layoutSubviews() {
    super.layoutSubviews()

    if let image = imageView?.image {

        let margin = 30 - image.size.width / 2
        let titleRect = titleRectForContentRect(bounds)
        let titleOffset = (bounds.width - titleRect.width - image.size.width - margin) / 2


        contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
            imageEdgeInsets = UIEdgeInsetsMake(0, margin, 0, 0)
            titleEdgeInsets = UIEdgeInsetsMake(0, (bounds.width - titleRect.width -  image.size.width - margin) / 2, 0, 0)
    }

}
其中一个技巧是:

  • 重写
    titlelectforcontentrect
    ,使按钮的
    标题标签
  • 等于按钮的边界
  • 将标题标签
    文本对齐设置为
    .Center
  • 覆盖
    imageRectForContentRect
    以指定按钮
    imageView的
    origin.x

    import UIKit
    
    class ButtonWithLeftAlignedImageAndCenteredText: UIButton {
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            titleLabel?.textAlignment = .Center
        }
    
        override func imageRectForContentRect(contentRect: CGRect) -> CGRect {
            var imageFrame = super.imageRectForContentRect(contentRect)
            imageFrame.origin.x = 20 //offset from left edge
            return imageFrame
        }
    
        override func titleRectForContentRect(contentRect:CGRect) -> CGRect {
            var titleFrame = super.titleRectForContentRect(contentRect)
            titleFrame = self.bounds
            return titleFrame
        }
    
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    

  • 您可以使用以下代码左对齐UIButton上的图像:-

    步骤1:

    //create your UIButton
    UIButton *post_bNeeds_BTN= [UIButton buttonWithType:UIButtonTypeRoundedRect];
    post_bNeeds_BTN.frame= CGRectMake(160 ,5 ,150 ,40);
    [post_bNeeds_BTN addTarget:self action:@selector(post_Buying_Needs_BTN_Pressed:) forControlEvents:UIControlEventTouchUpInside];
    [post_bNeeds_BTN setBackgroundColor:[UIColor colorWithRed:243/255.0 green:131/255.0 blue:26/255.0 alpha:1.0f]];//230
    [self.view addSubview:post_bNeeds_BTN];
    post_bNeeds_BTN.autoresizingMask= UIViewAutoresizingFlexibleWidth;
    
    步骤2:

    //Add UIImageView on right side the button
    UIImageView *bNeedsIVw= [[UIImageView alloc] initWithFrame:CGRectMake(5,5,30,30)];
    bNeedsIVw.image= [UIImage imageNamed:@"postRequir_30.png"];
    bNeedsIVw.image= [bNeedsIVw.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    bNeedsIVw.tintColor= [UIColor whiteColor];
    [post_bNeeds_BTN addSubview:bNeedsIVw];
    
    步骤3:

    //also set UILable on UIButton
    UILabel *bNeedsLbl= [[UILabel alloc] initWithFrame:CGRectMake(40 ,0 ,post_Prod_BTN.frame.size.width-40 ,post_Prod_BTN.frame.size.height)];
    bNeedsLbl.text= @"Requirements";
    bNeedsLbl.font= [UIFont systemFontOfSize:16];
    bNeedsLbl.textColor= [UIColor whiteColor];
    bNeedsLbl.textAlignment= NSTextAlignmentLeft;
    [post_bNeeds_BTN addSubview:bNeedsLbl];
    
    步骤4:

    -(void)post_Buying_Needs_BTN_Pressed:(id)sender{
        //write your code action here,,
    }
    

    谢谢,

    我用swift写了一个UIButton扩展名-

    extension UIButton {
    
    func setLeftImage(imageName:String, padding:CGFloat) {
            //Set left image
            let image = UIImage(named: imageName)
            self.setImage(image, forState: .Normal)
    
            //Calculate and set image inset to keep it left aligned
            let imageWidth = image?.size.width
            let textWidth = self.titleLabel?.intrinsicContentSize().width
            let buttonWidth = CGRectGetWidth(self.bounds)
    
            let padding:CGFloat = 30.0
            let rightInset = buttonWidth - imageWidth!  - textWidth! - padding
    
            self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: rightInset)
        }
    }
    
    我会以任何我想要的方式设计我的按钮文本,使其保持中心对齐。 然后我会在我的按钮上调用这个方法-

    myButton.setLeftImage("image_name", 30.0)
    
    这将导致我的图像与左边框的一些填充物左对齐

    [self.button setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
    
    [self.button setTitleEdgeInsets:UIEdgeInsetsMake(0.0, self.button.center.x/2 , 0.0, 0.0)];
    
    [self.button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    
    如果它不起作用,请告诉我

    我的输出


    此代码使按钮图像向左对齐,并且标题标签移动到按钮的中心。b是按钮:)


    此解决方案与Swift 3配合使用,尊重原始内容和图像边缘插入,同时使标题标签始终位于可用空间的中心,从而更容易调整边距

    它重写
    titleRect(forContentRect:)
    方法并返回正确的帧:

    @IBDesignable
    class LeftAlignedIconButton: UIButton {
        override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
            let titleRect = super.titleRect(forContentRect: contentRect)
            let imageSize = currentImage?.size ?? .zero
            let availableWidth = contentRect.width - imageEdgeInsets.right - imageSize.width - titleRect.width
            return titleRect.offsetBy(dx: round(availableWidth / 2), dy: 0)
        }
    }
    
    以下插图:

    这将导致:


    不推荐以前的答案

    这在大多数情况下都有效,但某些布局会导致
    layoutSubviews
    在无休止的循环中递归调用自身,因此请谨慎使用

    @IBDesignable
    class LeftAlignedIconButton: UIButton {
        override func layoutSubviews() {
            super.layoutSubviews()
            contentHorizontalAlignment = .left
            let availableSpace = UIEdgeInsetsInsetRect(bounds, contentEdgeInsets)
            let availableWidth = availableSpace.width - imageEdgeInsets.right - (imageView?.frame.width ?? 0) - (titleLabel?.frame.width ?? 0)
            titleEdgeInsets = UIEdgeInsets(top: 0, left: availableWidth / 2, bottom: 0, right: 0)
        }
    }
    
    此代码将执行相同的操作,但将图标对齐到右边缘:

    @IBDesignable
    class RightAlignedIconButton: UIButton {
        override func layoutSubviews() {
            super.layoutSubviews()
            semanticContentAttribute = .forceRightToLeft
            contentHorizontalAlignment = .right
            let availableSpace = UIEdgeInsetsInsetRect(bounds, contentEdgeInsets)
            let availableWidth = availableSpace.width - imageEdgeInsets.left - (imageView?.frame.width ?? 0) - (titleLabel?.frame.width ?? 0)
            titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: availableWidth / 2)
        }
    }
    


    正确的allignment版本使用了
    语义内容属性
    ,因此它需要iOS 9+。

    我知道这个答案有点晚了。 但我有一个非常简单的解决方案,适用于那些想使用UIImageView在UIButton左侧添加图像的人,该按钮的文本居中。全部以编程方式

    class RandomVC: UIViewController{
    
        var imageDemo: UIImageView = {
        let img = UIImageView()
        img.translatesAutoresizingMaskIntoConstraints = false
        img.image = UIImage(named: "someImgFromAssets")
        return img
        }()
    
        lazy var someButton: UIButton = { //lazy var: so button can have access to self class
        let button = UIButton(type: .system)
        button.setTitle("This is your title", for: UIControlState.normal)
        button.translatesAutoresizingMaskIntoConstraints = false 
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.addTarget(self, action: #selector(handleButtonClick), for: .touchUpInside) //make sure you write function "handleButtonClick" inside your class
        button.titleLabel?.textAlignment = .center
        return button
        }()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            view.addSubView(someButton)
            someButton.addSubview(imageDemo)
            imageDemo.centerYAnchor.constraint(equalTo: someButton.centerYAnchor).isActive = true
            imageDemo.leftAnchor.constraint(equalTo: someButton.leftAnchor, constant: 10).isActive = true
            imageDemo.heightAnchor.constraint(equalToConstant: 25).isActive = true
            imageDemo.widthAnchor.constraint(equalToConstant: 25).isActive = true
        }
    
    }
    

    我写了一个UIButton扩展

    扩展按钮{
    ///在左视图上添加图像
    func leftImage(图像:UIImage){
    self.setImage(图像,用于:。正常)
    self.imageEdgeInsets=UIEdgeInsets(顶部:0,左侧:0,底部:0,右侧:image.size.width)
    }
    }
    
    你可以这样使用:

    yourButton.leftImage(image: yourImage)
    

    我尝试了上面的几乎所有解决方案,但没有一个像我预期的那样有效(我有两个按钮,每个按钮都有不同的标题和不同的图像宽度)。因此,我为UIButton编写了自己的扩展,它可以完美地处理不同的图像宽度以及不同的标题

    extension UIButton {
        func moveImageLeftTextCenter(imagePadding: CGFloat = 30.0, titlePadding: CGFloat = 0.0, minImageTitleDistance: CGFloat = 10.0){
        guard let imageViewWidth = imageView?.frame.width else{return}
        guard let titleLabelWidth = titleLabel?.intrinsicContentSize.width else{return}
        contentHorizontalAlignment = .left
    
        let imageLeftInset = imagePadding - imageViewWidth / 2
        var titleLeftInset = (bounds.width - titleLabelWidth) / 2 - imageViewWidth + titlePadding
    
        if titleLeftInset - imageLeftInset < minImageTitleDistance{
            titleLeftInset = imageLeftInset + minImageTitleDistance
        }
    
        imageEdgeInsets = UIEdgeInsets(top: 0.0, left: imageLeftInset, bottom: 0.0, right: 0.0)
        titleEdgeInsets = UIEdgeInsets(top: 0.0, left: titleLeftInset, bottom: 0.0, right: 0.0)
        }
    }
    
    扩展按钮{
    func moveImageLeftTextCenter(图像填充:CGFloat=30.0,标题添加:CGFloat=0.0,最小标题距离:CGFloat=10.0){
    guard let imageViewWidth=imageView?.frame.width else{return}
    guard let titleLabelWidth=titleLabel?.intrinsicContentSize.width else{return}
    contentHorizontalAlignment=.left
    让imageLeftInset=imagePadding-imageViewWidth/2
    变量titleleftintset=(bounds.width-titleLabelWidth)/2-imageViewWidth+titlePadding
    如果标题左侧设置-图像左侧插入<最小标题距离{
    titleLeftInset=imageLeftInset+最小标题距离
    }
    imageEdgeInsets=UIEdgeInsets(顶部:0.0,左侧:imageLeftInset,底部:0.0,右侧:0.0)
    titleEdgeInsets=UIEdgeInsets(顶部:0.0,左侧:titleLeftInset,底部:0.0,右侧:0.0)
    }
    }
    
    用法:
    myButton.moveImag
    
    class RandomVC: UIViewController{
    
        var imageDemo: UIImageView = {
        let img = UIImageView()
        img.translatesAutoresizingMaskIntoConstraints = false
        img.image = UIImage(named: "someImgFromAssets")
        return img
        }()
    
        lazy var someButton: UIButton = { //lazy var: so button can have access to self class
        let button = UIButton(type: .system)
        button.setTitle("This is your title", for: UIControlState.normal)
        button.translatesAutoresizingMaskIntoConstraints = false 
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.addTarget(self, action: #selector(handleButtonClick), for: .touchUpInside) //make sure you write function "handleButtonClick" inside your class
        button.titleLabel?.textAlignment = .center
        return button
        }()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            view.addSubView(someButton)
            someButton.addSubview(imageDemo)
            imageDemo.centerYAnchor.constraint(equalTo: someButton.centerYAnchor).isActive = true
            imageDemo.leftAnchor.constraint(equalTo: someButton.leftAnchor, constant: 10).isActive = true
            imageDemo.heightAnchor.constraint(equalToConstant: 25).isActive = true
            imageDemo.widthAnchor.constraint(equalToConstant: 25).isActive = true
        }
    
    }
    
    yourButton.leftImage(image: yourImage)
    
    extension UIButton {
        func moveImageLeftTextCenter(imagePadding: CGFloat = 30.0, titlePadding: CGFloat = 0.0, minImageTitleDistance: CGFloat = 10.0){
        guard let imageViewWidth = imageView?.frame.width else{return}
        guard let titleLabelWidth = titleLabel?.intrinsicContentSize.width else{return}
        contentHorizontalAlignment = .left
    
        let imageLeftInset = imagePadding - imageViewWidth / 2
        var titleLeftInset = (bounds.width - titleLabelWidth) / 2 - imageViewWidth + titlePadding
    
        if titleLeftInset - imageLeftInset < minImageTitleDistance{
            titleLeftInset = imageLeftInset + minImageTitleDistance
        }
    
        imageEdgeInsets = UIEdgeInsets(top: 0.0, left: imageLeftInset, bottom: 0.0, right: 0.0)
        titleEdgeInsets = UIEdgeInsets(top: 0.0, left: titleLeftInset, bottom: 0.0, right: 0.0)
        }
    }
    
    extension UIButton {
    
      func leftImage(image: UIImage, renderMode: UIImage.RenderingMode) {
           self.setImage(image.withRenderingMode(renderMode), for: .normal)
           self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
           self.titleEdgeInsets.left = (self.frame.width/2) - (self.titleLabel?.frame.width ?? 0)
           self.contentHorizontalAlignment = .left
           self.imageView?.contentMode = .scaleAspectFit
       }
        
        func rightImage(image: UIImage, renderMode: UIImageRenderingMode){
            self.setImage(image.withRenderingMode(renderMode), for: .normal)
            self.imageEdgeInsets = UIEdgeInsets(top: 0, left:image.size.width / 2, bottom: 0, right: 0)
            self.contentHorizontalAlignment = .right
            self.imageView?.contentMode = .scaleAspectFit
        }
    }
    
    myButton.rightImage(image: UIImage(named: "image_name")!, renderMode: .alwaysOriginal)
    myButton.leftImage(image: UIImage(named: "image_name")!, renderMode: .alwaysOriginal)
    
    extension UIButton {
        func leftImage(image: UIImage, renderMode: UIImage.RenderingMode) {
            self.setImage(image.withRenderingMode(renderMode), for: .normal)
            self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: image.size.width / 2)
            self.contentHorizontalAlignment = .left
            self.imageView?.contentMode = .scaleAspectFit
        }
        
        func rightImage(image: UIImage, renderMode: UIImage.RenderingMode){
            self.setImage(image.withRenderingMode(renderMode), for: .normal)
            self.imageEdgeInsets = UIEdgeInsets(top: 0, left:image.size.width / 2, bottom: 0, right: 0)
            self.contentHorizontalAlignment = .right
            self.imageView?.contentMode = .scaleAspectFit
        }
    }
    
    let width = frame.width
    guard let imageWidth = imageView?.frame.width, let labelWidth = titleLabel?.frame.width else {
          return
    }
    titleEdgeInsets = UIEdgeInsets(top: 0, left: (width - labelWidth)/2.0 - imageWidth, bottom: 0, right: 0)
    
    func leftImage(image: UIImage, padding: CGFloat, renderMode: UIImage.RenderingMode) {
        self.setImage(image.withRenderingMode(renderMode), for: .normal)
        contentHorizontalAlignment = .left
        let availableSpace = bounds.inset(by: contentEdgeInsets)
        let availableWidth = availableSpace.width - imageEdgeInsets.right - (imageView?.frame.width ?? 0) - (titleLabel?.frame.width ?? 0)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: availableWidth / 2, bottom: 0, right: 0)
        imageEdgeInsets = UIEdgeInsets(top: 0, left: padding, bottom: 0, right: 0)
    }
    
    func rightImage(image: UIImage, padding: CGFloat, renderMode: UIImage.RenderingMode){
        self.setImage(image.withRenderingMode(renderMode), for: .normal)
        semanticContentAttribute = .forceRightToLeft
        contentHorizontalAlignment = .right
        let availableSpace = bounds.inset(by: contentEdgeInsets)
        let availableWidth = availableSpace.width - imageEdgeInsets.left - (imageView?.frame.width ?? 0) - (titleLabel?.frame.width ?? 0)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: availableWidth / 2)
        imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: padding)
    }
    
    import UIKit
    
    extension UIButton {
        func moveImageLeftTextCenter(image : UIImage, imagePadding: CGFloat, renderingMode: UIImage.RenderingMode){
            self.setImage(image.withRenderingMode(renderingMode), for: .normal)
            guard let imageViewWidth = self.imageView?.frame.width else{return}
            guard let titleLabelWidth = self.titleLabel?.intrinsicContentSize.width else{return}
            self.contentHorizontalAlignment = .left
            let imageLeft = imagePadding - imageViewWidth / 2
            let titleLeft = (bounds.width - titleLabelWidth) / 2 - imageViewWidth
            imageEdgeInsets = UIEdgeInsets(top: 0.0, left: imageLeft, bottom: 0.0, right: 0.0)
            titleEdgeInsets = UIEdgeInsets(top: 0.0, left: titleLeft , bottom: 0.0, right: 0.0)
        }
    }
    
    class CustomButton: UIButton {
    
        var imageV = UIImageView()
        var titleV = UILabel()
    
        override func awakeFromNib() {
    
            self.imageView?.isHidden = true
            self.titleLabel?.isHidden = true
    
            imageV.frame = CGRect(x: 0, y: 0, width: 40, height: self.bounds.height)
            imageV.contentMode = .scaleAspectFit
    
            titleV.frame = CGRect(x: 40, y: 0, width: self.bounds.width - 40, height: self.bounds.height)
            titleV.font = self.titleLabel?.font
            titleV.textAlignment = .center
    
            self.addSubview(imageV)
            self.addSubview(titleV)
    
            imageV.image = self.imageView?.image; titleV.text = self.titleLabel?.text
    
            imageV.translatesAutoresizingMaskIntoConstraints = false
            imageV.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
            imageV.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
            imageV.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
            imageV.trailingAnchor.constraint(equalTo: titleV.leadingAnchor, constant: 0).isActive = true
            imageV.widthAnchor.constraint(equalToConstant: 40).isActive = true
    
            titleV.translatesAutoresizingMaskIntoConstraints = false
            titleV.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
            titleV.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
            titleV.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
        }
    }
    
    button.imageV.image = myImage
    button.titleV.text = myText
    
    class CustomButton : UIButton {
    
        @IBInspectable var alignImageToLeft : Bool = false
    
        override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
            if(alignImageToLeft){
                let imageRect = super.imageRect(forContentRect: contentRect)
                let offset = contentRect.minX - imageRect.minX
                return imageRect.offsetBy(dx: offset, dy: 0.0)
            }
            return super.imageRect(forContentRect: contentRect)
        }
    }
    
    var button = UIButton()
    
    newGameButton.setTitle("Новая игра", for: .normal)
    newGameButton.setImage(UIImage(named: "energi"), for: .normal)
    newGameButton.backgroundColor = .blue
    newGameButton.imageEdgeInsets.left = -50
    
       override func layoutSubviews() {
           super.layoutSubviews()
           
           if let label = titleLabel {
               label.frame = label.frame.offsetBy(dx: super.bounds.midX - 
                    label.frame.midX , dy: 0)
           }
    
           // Available space to the left of the titleLabel is simply:
           let leftAvailableWidth = label.frame.minX
    
           imageView?.frame = CGRect(x: 0, y: 0, width: <Some width smaller than leftAvailableWidth>, height: super.bound.height)
       }