2016-12-15 2 views
-1

Я новичок в iOS и Swift, и мне нужна помощь.создать пользовательский UIButton с помощью расширения

Я хочу, чтобы создать пользовательский UIButton

Вот что я сделал

protocol ButtonProtocol {} 


extension ButtonProtocol where Self: UIButton { 

    func addOrangeButton(){ 
     layer.cornerRadius = 8 
     layer.backgroundColor = UIColor(netHex:ButtonColor.orange).cgColor 
    } 
} 

Я хочу, чтобы все PARAMS пришли сюда которые cornerRadius, backgrounColor, highlightedColor, TextColor, размер и т.д. ...

Я хочу использовать этот способ bcoz, возможно, в будущем цвет кнопки изменится, я изменю его с одного места напрямую.

Но я не понимаю, что такое слой, как я могу использовать его как UIButton?

Может ли кто-нибудь сказать мне, в каком виде я должен взять?

ответ

2

Вы можете создать подкласс UIButton, чтобы добавить свой собственный стиль к вашей кнопке. например,

import UIKit 

protocol DVButtonCustomMethods: class { 
func customize() 
} 

class DVButton: UIButton { 
var indexPath: IndexPath? 

override init(frame: CGRect) { 
    super.init(frame: frame) 
    customize()// To set the button color and text size 
} 

required init?(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 
    customize()// To set the button color and text size 
} 

override func layoutSubviews() { 
    super.layoutSubviews() 
    customize() 
} 

} 

extension DVButton: DVButtonCustomMethods { 
func customize() { 
    layer.cornerRadius = self.frame.size.height/2 
    backgroundColor = UIColor.white 
    tintColor = UIColor.red 
    titleLabel?.textColor = UIColor.black 
    clipsToBounds = true 
} 
} 

Теперь, что нужно сделать, создайте одну кнопку в построителе интерфейса и назначьте подкласс как свой класс. То, что все изменится, как вы хотите. Если вы хотите изменить цвет кнопки, просто измените свой подкласс, это повлияет на все кнопки, которым назначен ваш подкласс.

Назначение подкласса вашей кнопки: см ниже изображения

enter image description here

Спасибо :)

0

Попробуйте это:

class func CutomeButton(bgColor: UIColor,corRadius: Float,hgColor: UIColor, textColor: UIColor, size: CGSize, titleText: String) -> UIButton { 
    let button = UIButton() 
    button.layer.cornerRadius = CGFloat(corRadius) 
    button.backgroundColor = bgColor 
    button.setTitleColor(textColor, for: .normal) 
    button.frame.size = size 
    button.setTitle(titleText, for: .normal) 
    return button 
} 
0

Если я хорошо понимаю, вы хотите изменить UIButton с определенными параметрами, позвольте мне рассказать вам, как это сделать:

extension UIButton 
{ 
    func setRadius(radius:CGFloat) { 
     self.layer.cornerRadius = radius 
    } 
} 

Используйте его как следующее:

yourButton.setRadius(radius: 15) 
1

, как вы определили расширение, не делает вас в состоянии использовать его в UIButton например так просто.

Таким образом, вы можете решить, следует ли расширить UIButton в соответствии с протоколом, или вы можете создать подкласс UIButton

// in this way you can use the `addOrangeButton` method anywhere 
extension UIButton: ButtonProtocol {} 

// in this way your new subclass contains the addOrangeButton definition 
// and a normal UIButton cannot access that method 
final class OrangeButton: UIButton, ButtonProtocol { 

    func setupButton() { 
     addOrangeButton() 
    } 
} 
Смежные вопросы