一 概述
本文介绍给UIButton设置background图片,并设置点击高亮时的图片,并通过上下左右按钮,控制UIButton上下左右移动
二 界面布局
- 将图片资源拖放到Assets.xcassets目录下
- 在main.storyboard上布局如下
三 代码实现
3.1 OC
3.1.1 ViewController.h
1 2 3 4
| #import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (weak, nonatomic) IBOutlet UIButton *iconButton; @end
|
3.1.2 ViewController.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| #import "ViewController.h"
@interface ViewController ()
@end typedef enum { moveDirTop=11, moveDirLeft=12, moveDirBottom=13, moveDirRight=14 }moveDirect;
#define moveDelta 20;
@implementation ViewController - (IBAction)move:(UIButton*)button { CGRect frame=self.iconButton.frame; switch (button.tag) { case moveDirTop: frame.origin.y-=moveDelta; break; case moveDirLeft: frame.origin.x-=moveDelta; break; case moveDirBottom: frame.origin.y+=moveDelta; break; case moveDirRight: frame.origin.x+=moveDelta; break; default: break; } self.iconButton.frame=frame; }
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. } @end
|
3.2 Swift实现
3.2.1 ViewController.swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| import UIKit
enum moveDir:Int { case moveTop = 11 case moveLeft = 12 case moveBottom = 13 case moveRight = 14 } let moveLata:Double = 20.0
class ViewController: UIViewController {
@IBOutlet weak var moveButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func move(_ button: UIButton) { var frame:CGRect=self.moveButton.frame switch button.tag { case moveDir.moveTop.rawValue: frame.origin.y-=CGFloat(moveLata) break case moveDir.moveLeft.rawValue: frame.origin.x-=CGFloat(moveLata) break; case moveDir.moveBottom.rawValue: frame.origin.y+=CGFloat(moveLata) break; case moveDir.moveRight.rawValue: frame.origin.x+=CGFloat(moveLata) break; default: break; } moveButton.frame = frame } }
|