Align button image to right edge of UIButton

前端 未结 14 2176
野趣味
野趣味 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:41

    Try below code:

    btn.contentHorizontalAlignment = .right
    
    0 讨论(0)
  • 2020-12-07 23:41

    Simple way

    Using extension to set image on the right side with custom offset

       extension UIButton {
        func addRightImage(image: UIImage, offset: CGFloat) {
            self.setImage(image, for: .normal)
            self.imageView?.translatesAutoresizingMaskIntoConstraints = false
            self.imageView?.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0.0).isActive = true
            self.imageView?.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -offset).isActive = true
        }
    }
    
    0 讨论(0)
  • 2020-12-07 23:47

    Semantic: Force Right-to-Left on View works for me

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

    make it as default semantic i.e unspecified or force left to right

    and in button.imageEdgeInsets set it as

    UIEdgeInsets(top: 0, left: self.view.frame.size.width - (the image size + the alignment space ) , bottom: 0, right: 0)

    this will make ensure that no matter what the view size is ,it will always align the image from right side of the button

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

    SWIFT 5

    button.imageEdgeInsets = UIEdgeInsets(top: 0, left: (bounds.width - 16), bottom: 0, right: 0)
    
    0 讨论(0)
  • 2020-12-07 23:53

    It's working for me:

    self.acceptButton.setImage(UIImage(named: image), for: UIControl.State.normal)
    self.acceptButton.semanticContentAttribute = .forceRightToLeft
    self.acceptButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 9, bottom: 0, right: 0)
    
    0 讨论(0)
提交回复
热议问题