iOS - UIButton系统选定的图像

iOS - UIButton系统选定的图像

问题描述:

我有一个UIButton,带有一个透明的图像,并带有切换选择。 在当前配置中,我使用系统按钮类型,因为它很好地反转了按钮。然而,通过这种反转,我得到一个带有边框的图像,并且我希望这个图像填充整个按钮。这怎么能实现?我想保留系统的透明遮罩。iOS - UIButton系统选定的图像

Here is the repository.

在下面的图像是所选系统的状态是什么样子。

enter image description here

+0

从图像和按钮想要什么一件事? –

+0

我想要iOS添加的圆角矩形来反转所选按钮,以填充整个按钮框。 –

+0

sry,它对我不清楚。 –

创建的UIButton的子类并覆盖isSelected

对于实例

class CustomButton: UIButton { 

    /* 
    // Only override draw() if you perform custom drawing. 
    // An empty implementation adversely affects performance during animation. 
    override func draw(_ rect: CGRect) { 
     // Drawing code 
    } 
    */ 




    override var isSelected: Bool { 


     didSet { 
      if isSelected { 
       self.backgroundColor = UIColor.blue 
       self.tintColor = UIColor.white 
      } else { 
       self.backgroundColor = .white 
       self.tintColor = UIColor.red 
      } 

     } 
    } 

} 

更改颜色根据您的要求

,并考虑控制得很不喜欢这个

class ViewController: UIViewController { 

@IBOutlet weak var button: CustomButton! 
override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    button.isSelected = false 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 
@IBAction func btnTapped(_ sender: Any) { 
    button.isSelected = !button.isSelected 
} 

}

还有就是你要设置渲染图像的选项模板Template Image

+0

适用于白色背景,但是图像背景怎么样? –

+0

你必须使它们变白,并在运行时应用颜色 –