swift学习笔记-UI篇之UIButton

1. 基本使用

//1. 创建button
let button = UIButton(type: UIButtonType.Custom)
button.frame = CGRectMake(10, 100, 100, 100)
self.view.addSubview(button)

//2. 设置样式
button.backgroundColor = UIColor.greenColor()
/* UIControlState:按钮状态
    Normal: 正常状态
    Highlighted: 高亮状态
    Disabled: 不可用状态
    Selected: 选中状态
*/
// 设置正常状态下的标题
button.setTitle("button", forState: UIControlState.Normal)
// 设置标题颜色
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
// 设置图标
button.setImage(UIImage(named: "Comment_hongxin_dianji"), forState: UIControlState.Normal)
// 注意:tintColor在 UIButtonTypeCustom 时没有用,其它样式下影响image和title的颜色
// button.tintColor = UIColor.orangeColor()

2. button的图标和标题处理

//3. button的图标和标题处理
//1) 居中显示
//        button.titleEdgeInsets = UIEdgeInsetsMake(0, -button.imageView!.intrinsicContentSize().width, 0, 0)
//        button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -button.titleLabel!.intrinsicContentSize().width)
        
//        //2) 图标在上,标题在下居中显示,中间空10的距离
//        button.titleEdgeInsets = UIEdgeInsetsMake(0, -button.imageView!.intrinsicContentSize().width, -(button.imageView!.intrinsicContentSize().height+10.0/2.0), 0)
//        button.imageEdgeInsets = UIEdgeInsetsMake(-(button.titleLabel!.intrinsicContentSize().height+10.0/2.0), 0, 0, -button.titleLabel!.intrinsicContentSize().width)
//        
//        //3) 图标在右,标题在左
//        button.titleEdgeInsets = UIEdgeInsetsMake(0, -button.intrinsicContentSize().width-button.imageView!.intrinsicContentSize().width+button.titleLabel!.intrinsicContentSize().width, 0, 0)
//        button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -button.intrinsicContentSize().width-button.titleLabel!.intrinsicContentSize().width+button.imageView!.intrinsicContentSize().width)

3. 代码下载

https://github.com/ljcoder2015/SwiftStudyNote/tree/master/swift-UIButton

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,301评论 4 61
  • 坏情绪像弹簧越压越强 这本出自美国心理治疗师迪娜·吉尔伯特森的自助心理学作品从一开始就开门见山的指出来: 学会和你...
    药山阅读 1,224评论 2 50
  • 〖简介:一个普通的上班族澄子卷入了两场命案。澄子偶遇房地产推销员高中同学海子,海子向澄子承诺,如果卖出公司脑子搞定...
    木子吹疯阅读 371评论 0 0
  • 美丽的如意池边,鸳鸯小憩,绿水相映,相许终生!玉石清泉,叙不尽未了情缘!
    凌薇言阅读 272评论 1 15