IOS 按钮(button)用法与属性实例

转载请注明出处:http://blog.csdn.net/linux_zkf

IOS 按钮(button)用法与属性实例

- (void) toggleButton: (UIButton *) button

{

if (isOn = !isOn)

{

[button setTitle:@"On" forState:UIControlStateNormal];

[button setTitle:@"On" forState:UIControlStateHighlighted];

[button setBackgroundImage:baseGreen forState:UIControlStateNormal];

[button setBackgroundImage:altGreen forState:UIControlStateHighlighted];

}

else

{

[button setTitle:@"Off" forState:UIControlStateNormal];

[button setTitle:@"Off" forState:UIControlStateHighlighted];

[button setBackgroundImage:baseRed forState:UIControlStateNormal];

[button setBackgroundImage:altRed forState:UIControlStateHighlighted];

}

}

- (void) viewDidLoad

{

float capWidth = 110.0f;

baseGreen = [[[UIImage imageNamed:@"green.png"stretchableImageWithLeftCapWidth:capWidthtopCapHeight:0.0fretain];

baseRed = [[[UIImage imageNamed:@"red.png"stretchableImageWithLeftCapWidth:capWidthtopCapHeight:0.0fretain];

altGreen = [[[UIImage imageNamed:@"green2.png"stretchableImageWithLeftCapWidth:capWidthtopCapHeight:0.0fretain];

altRed = [[[UIImage imageNamed:@"red2.png"stretchableImageWithLeftCapWidth:capWidthtopCapHeight:0.0fretain];

// 创建

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

button.frame = CGRectMake(0.0f0.0f300.0f233.0f);

button.center = CGPointMake(160.0f140.0f);

// 设置aligment 属性

button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

//button.titleLabel.textAlignment = UITextAlignmentCenter;

//设置title自适应对齐

button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;

// 设置颜色和字体

[button setTitleColor:[UIColor whiteColorforState:UIControlStateNormal];

[button setTitleColor:[UIColor lightGrayColorforState:UIControlStateHighlighted];

button.titleLabel.font = [UIFont boldSystemFontOfSize:24.0f];

// 添加 action

[button addTarget:self action:@selector(toggleButton:) forControlEventsUIControlEventTouchUpInside];

    //设置title

    [button setTitle:@"On" forState:UIControlStateNormal];

    [button setTitle:@"On" forState:UIControlStateHighlighted];

    //设置背景

    [button setBackgroundImage:baseGreen forState:UIControlStateNormal];

    [button setBackgroundImage:altGreen forState:UIControlStateHighlighted];

// 用于测试的BOOL

isOn = NO;


// button放入view

[self.view addSubview:button];

}


你可能感兴趣的:(IOS 按钮(button)用法与属性实例)