我是子类化的UIButton,我想要的是设置按钮类型为圆角矩形。
Button.h
@interface Button : UIButton {}
- (void)initialize;
@endButton.m
@implementation Button
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self initialize];
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if(self){
[self initialize];
}
return self;
}
- (void)initialize
{
self.titleLabel.font = [UIFont systemFontOfSize:20];
self.titleLabel.textColor = [UIColor redColor];
self.titleLabel.textAlignment = UITextAlignmentCenter;
//[UIButton buttonWithType:UIButtonTypeRoundedRect];
}
@end在这里我尝试了[UIButton buttonWithType:UIButtonTypeRoundedRect],但它不起作用。有没有人能建议如何让它工作?
我知道在很多以前的文章中,有人说不推荐对UIButton进行子类化,但事实上在开发人员文档中并没有提到不对其进行子类化。
发布于 2012-04-23 18:07:38
您可能会发现CocoaBuilder线程How to subclass UIButton?上的讨论很有帮助,尤其是Jack Nutting's suggestion to ignore the buttonType
注意,这种方式不会将buttonType显式设置为任何值,这可能意味着它是UIButtonTypeCustom。文档似乎并没有指定这一点,但由于这是枚举中的0值,所以很可能会发生这种情况(这似乎也是可观察到的行为)
发布于 2017-02-18 07:10:03
Swift中的UIButton子类
*以下代码适用于Swift 3及更高版本。
不能通过设计来设置UIButton子类的buttonType。它会自动设置为custom,这意味着您将获得一个简单的外观和行为作为起点。
如果您希望重用设置按钮外观的代码,则可以在不创建子类的情况下完成此操作。一种方法是通过提供工厂方法来创建UIButton和设置可视属性。
避免子类化的示例工厂方法
extension UIButton {
static func createStandardButton() -> UIButton {
let button = UIButton(type: UIButtonType.system)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
button.setTitleColor(UIColor.black, for: .normal)
button.setTitleColor(UIColor.gray, for: .highlighted)
return button
}
}
let button = UIButton.createStandardButton()当其他定制技术足够时,我避免将UIButton子类化。工厂方法示例是一种选择。还有其他选项,包括UIAppearance应用程序接口等。
有时,有一些定制需求需要子类化。例如,我创建了UIButton子类来精细控制按钮如何响应触摸事件的动画,或者让按钮在被点击时调用预定义的委托或闭包(而不是为每个实例分配一个#selector )。
下面是一个基本的UIButton子类示例作为起点。
示例UIButton子类
internal class CustomButton: UIButton {
init() {
// The frame can be set outside of the initializer. Default to zero.
super.init(frame: CGRect.zero)
initialize()
}
required init?(coder aDecoder: NSCoder) {
// Called when instantiating from storyboard or nib
super.init(coder: aDecoder)
initialize()
}
func initialize() {
print("Execute common initialization code")
}
}
let button = CustomButton()
print(button.buttonType == .custom) // true关于UIButtonType的说明
自从这个问题在2012年被提出以来,UIButtonType.roundedRect已经被弃用了。头文件注释表明应该使用UIButtonType.system。
下面是UIButton.h在Xcode中转换为Swift的代码
public enum UIButtonType : Int {
case custom // no button type
@available(iOS 7.0, *)
case system // standard system button
case detailDisclosure
case infoLight
case infoDark
case contactAdd
public static var roundedRect: UIButtonType { get } // Deprecated, use UIButtonTypeSystem instead
}发布于 2013-09-13 00:26:30
不完全是您想要的,但是请记住,您的子类仍然具有buttonWithType方法,并且它工作得很好。
buttonWithType调用您的子类initWithFrame,并相应地设置类型。
SubclassButton *myButton=[SubclassButton buttonWithType:UIButtonTypeRoundedRect];https://stackoverflow.com/questions/10277863
复制相似问题