Align button image to right edge of UIButton

前端 未结 14 2187
野趣味
野趣味 2020-12-07 23:05

There are plenty of threads about aligning a button image according to the title text, but I can\'t find anything about just aligning the image to the right side of the butt

相关标签:
14条回答
  • 2020-12-07 23:30

    Clean way to do this in Swift

    button.semanticContentAttribute = .forceRightToLeft
    

    Hope this helps

    0 讨论(0)
  • 2020-12-07 23:31

    I found a tricky way Update the constrains for the UIImageView of the Button

    try this

    button.imageView?.trailingAnchor.constraint(equalTo: button.trailingAnchor, constant: -8.0).isActive = true
    button.imageView?.centerYAnchor.constraint(equalTo: button.centerYAnchor, constant: 0.0).isActive = true
    

    but don't forget to add this to make the constrains effective

    button.translatesAutoresizingMaskIntoConstraints = false
    button.imageView?.translatesAutoresizingMaskIntoConstraints = false
    
    0 讨论(0)
  • 2020-12-07 23:35

    There are several different options to do it.

    Use semanticContentAttribute

    button.semanticContentAttribute = .forceRightToLeft
    

    You can set semantic attribute from interface (storyboard) layout also.


    or Use UIView containing UIButton and UIImage, as shown in this snapshot.

    • Set Image right side in UIView and disable user interaction, so user action/tap will be passed to button.
    • Add button with size same as UIView, in UIView, with transparent background color and covering Image.
    • Set content offset for button as shown in this snapshot.

    This will make easy to handle button action, properties and customise image position & size according to your requirement. Try this.

    0 讨论(0)
  • 2020-12-07 23:37

    This worked for me

    btn.imageView?.translatesAutoresizingMaskIntoConstraints = false
    btn.imageView?.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0.0).isActive = true
    btn.imageView?.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20).isActive = true
    
    0 讨论(0)
  • 2020-12-07 23:38

    This worked for me by setting:

    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    

    Then for the inner image I set the right inset to 0.

    button.imageEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 10.0, 0);
    
    0 讨论(0)
  • 2020-12-07 23:40

    To align an image to right, the 'Semantic' option seems the best, 'Force Right-to-Left'. Furthermore, I want to add one more thing. You can keep the shape of the button's image by this option.

    0 讨论(0)
提交回复
热议问题