swift 第四課

來源:互聯網
上載者:User

標籤:ace   view   frame   contents   type   led   str   tsm   float   

項目中經常遇到按鈕改變文字和圖片位置的情況,所以嘗試寫一個 button 的分類

import Foundationimport UIKit
/*
枚舉 設定 圖片的位置
*/enum ButtonImagePosition : Int{ case PositionTop = 0 case Positionleft case PositionBottom case PositionRight}extension UIButton {
/**
imageName:圖片的名字
title:button 的名字
type :image 的位置
Space :圖片文字之間的間距
*/ func setImageAndTitle(imageName:String,title:String,type:ButtonImagePosition,Space space:CGFloat) { self.setTitle(title, for: .normal) self.setImage(UIImage(named:imageName), for: .normal) let imageWith :CGFloat = (self.imageView?.frame.size.width)!; let imageHeight :CGFloat = (self.imageView?.frame.size.height)!; var labelWidth :CGFloat = 0.0; var labelHeight :CGFloat = 0.0; labelWidth = CGFloat(self.titleLabel!.intrinsicContentSize.width); labelHeight = CGFloat(self.titleLabel!.intrinsicContentSize.height);
var imageEdgeInsets :UIEdgeInsets = UIEdgeInsets(); var labelEdgeInsets :UIEdgeInsets = UIEdgeInsets(); switch type { case .PositionTop: imageEdgeInsets = UIEdgeInsetsMake(-labelHeight - space/2.0, 0, 0, -labelWidth); labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith, -imageHeight-space/2.0, 0); break; case .Positionleft: imageEdgeInsets = UIEdgeInsetsMake(0, -space/2.0, 0, space/2.0); labelEdgeInsets = UIEdgeInsetsMake(0, space/2.0, 0, -space/2.0); break; case .PositionBottom: imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight-space/2.0, -labelWidth); labelEdgeInsets = UIEdgeInsetsMake(-imageHeight-space/2.0, -imageWith, 0, 0); break; case .PositionRight: imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth+space/2.0, 0, -labelWidth-space/2.0); labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith-space/2.0, 0, imageWith+space/2.0); break; } // 4. 賦值 self.titleEdgeInsets = labelEdgeInsets; self.imageEdgeInsets = imageEdgeInsets; }}

 

swift 第四課

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.