UIButton+Extension.swift 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //
  2. // UIButton+Extension.swift
  3. // o2app
  4. //
  5. // Created by 刘振兴 on 2017/8/25.
  6. // Copyright © 2017年 zone. All rights reserved.
  7. //
  8. import UIKit
  9. extension UIButton {
  10. class func btn(bgColor: UIColor, disabledColor: UIColor, title: String, titleColor: UIColor) -> UIButton {
  11. let btn = UIButton(type: .custom)
  12. btn.frame = .zero
  13. let attribeTitle = NSAttributedString(string: title, attributes: [NSAttributedString.Key.foregroundColor:titleColor,NSAttributedString.Key.font:UIFont.init(name: "PingFangSC-Regular", size: 18)!])
  14. btn.setAttributedTitle(attribeTitle, for: .normal)
  15. btn.setAttributedTitle(attribeTitle, for: .disabled)
  16. btn.backgroundColor = bgColor
  17. btn.layer.cornerRadius = 3.0
  18. btn.layer.masksToBounds = true
  19. return btn
  20. }
  21. /// EZSwiftExtensions: Convenience constructor for UIButton.
  22. public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, target: AnyObject, action: Selector) {
  23. self.init(frame: CGRect(x: x, y: y, width: w, height: h))
  24. addTarget(target, action: action, for: UIControl.Event.touchUpInside)
  25. }
  26. /// EZSwiftExtensions: Set a background color for the button.
  27. public func setBackgroundColor(_ color: UIColor, forState: UIControl.State) {
  28. UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
  29. UIGraphicsGetCurrentContext()?.setFillColor(color.cgColor)
  30. UIGraphicsGetCurrentContext()?.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
  31. let colorImage = UIGraphicsGetImageFromCurrentImageContext()
  32. UIGraphicsEndImageContext()
  33. self.setBackgroundImage(colorImage, for: forState)
  34. }
  35. }