UIButton - 按钮

作为 几乎所有页面的常客,也稍微写一点东东,留下一点内容。(UIButton 继承自 UIControl,下次在研究哦)

基础创建 与 属性

// 创建一般使用 类方法,
    self.testButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    
// 设置一些 属性,并对应几个状态
    [self.testButton setTitle:@"点击测试" forState:UIControlStateNormal];
    [self.testButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.testButton setTitleShadowColor:[UIColor greenColor] forState:UIControlStateNormal];
    [self.testButton setImage:[UIImage imageNamed:@"jpg_test"] forState:UIControlStateNormal];
    [self.testButton setBackgroundImage:[UIImage imageNamed:@"jpg_test"] forState:UIControlStateHighlighted];
    
// 属性字符串 需要的话看另一篇 Foundation 中的 NSAttributedString 篇。
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"testAttributed" attributes:@{NSForegroundColorAttributeName:[UIColor blueColor],NSUnderlineStyleAttributeName:@(1)}];
    [self.testButton setAttributedTitle:attributedString forState:UIControlStateHighlighted];
    
  • 对应设置的属性,反过来也可以获取到属性内容
    只举一个例子,其他的返三吧。
// 对应状态的 title
    NSString *testButtonTitle = [self.testButton titleForState:UIControlStateNormal];

// 当前的 title
    NSString *testButtonCurrentTitle = [self.testButton currentTitle];

状态 - UIControlState 简单说明

注意:UIControlState 是 NS_OPTIONS 类型,所以注意下面第四个 比较特殊。在贴图片,而且会正常-选中 切换是可能会用到哦。

    [self.testButton setTitle:@"正常时" forState:UIControlStateNormal];
    [self.testButton setTitle:@"选中时" forState:UIControlStateSelected];
    [self.testButton setTitle:@"正常 高亮状态" forState:UIControlStateHighlighted];
    [self.testButton setTitle:@"选中时 高亮状态" forState:UIControlStateHighlighted | UIControlStateSelected];
    

内容位置调整 - UIEdgeInsets

  • 1 对button 的title 或者 image ,其一设置 UIEdgeInsets 时,比较方便好用。
  • 2 但是,由于 button 带有 title 和 image 2个属性,同时存在时,调整这两个属性用 UIEdgeInsets 不是很好用。他们2个本身就有一定的调整,而且与image 大小与button大小也有一定关系,推荐使用重绘。
    [self.testButton setTitleEdgeInsets:UIEdgeInsetsMake(10, 20, 30, 40)];
// 简单调整 title 位置 
// 关于位置调整偏移 查看 UIKit -  UIGeometry.h 类。

UIEdgeInsets- 重绘

- (CGRect)backgroundRectForBounds:(CGRect)bounds;
- (CGRect)contentRectForBounds:(CGRect)bounds;
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- (CGRect)imageRectForContentRect:(CGRect)contentRect;

简单举例:上面 2/3 是图片,下面1/3 是文字

- (CGRect)titleRectForContentRect:(CGRect)contentRect {
    return CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) * 2 / 3);
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect {
    return CGRectMake(0, CGRectGetHeight(self.bounds) * 2 / 3, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) / 3);
}

其他

    self.testButton.reversesTitleShadowWhenHighlighted = YES;// 文字阴影 高亮时反向
    
    self.testButton.showsTouchWhenHighlighted = YES; // 触摸 有 亮光
    self.testButton.adjustsImageWhenHighlighted = NO; // 图片 点击 不变灰
    self.testButton.adjustsImageWhenDisabled = NO; // 图片 失效 不变灰

addTarget:action:为啥木有?? 在 UIControl 类,另讲。

你可能感兴趣的:(UIButton - 按钮)