swift 自定义按钮

自定义按钮视图:上半部分显示图片,下半部分显示标题,效果:


swift 自定义按钮_第1张图片
圆形图片按钮.png

swift 自定义按钮_第2张图片
方形图片按钮.png
class CustomImageBtn: UIButton {
  var aboveImageView :UIImageView!
  var bottomLabel:UILabel!
  /**
   创建自定制按钮视图
   
   - parameter frame:    frame
   - parameter isRound:  图片是都是圆形
   
   - returns:  self
   */
  init(frame: CGRect,isRound:Bool) {
    super.init(frame: frame)
    let imageSide = self.frame.height-20-30
    let spaceX = (self.frame.width - imageSide)/2.0
    aboveImageView = UIImageView.init(frame: CGRectMake(spaceX, 10, imageSide, imageSide))
    aboveImageView.image = UIImage.init(named: "placeholder")
    if isRound {
      aboveImageView.layer.cornerRadius = imageSide/2.0
    }else{
      aboveImageView.layer.cornerRadius = 3.0
    }
    self.addSubview(aboveImageView)
    bottomLabel = UILabel.init(frame: CGRectMake(0, imageSide+20, self.frame.width, 20))
    bottomLabel.text = "标题"
    bottomLabel.textColor = UIColor.grayColor()
    bottomLabel.textAlignment = .Center
    bottomLabel.font = UIFont.systemFontOfSize(13)
    self.addSubview(bottomLabel)
  }
  
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  /**
   配置按钮
   - parameter imageUrlStr: 按钮的图片链接
   - parameter title:       按钮的标题
   */
  func configBtn(image:UIImage,title:String)  {
    aboveImageView.image = image
    bottomLabel.text = title
  }
}
    //添加自定义按钮
    let cusImageBtn = CustomImageBtn.init(frame: CGRectMake(0, 0, 100, 120), isRound: false)
    self.view.addSubview(cusImageBtn)
    cusImageBtn.configBtn(UIImage.init(named: "ICON108")!, title: "自定义按钮")

期待你的评论建议O(∩_∩)O~

你可能感兴趣的:(swift 自定义按钮)