swift - 如何缩放图像并将其置于 Swift 中的 UIButton 中心?

标签 swift uibutton

var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
var image = UIImage(named: "myimage.png") as UIImage!
button.frame = CGRectMake(0, 0, 100, 100)
button.setImage(image, forState: .Normal)

我在按钮上设置了一张图片,但我想将其缩放为小于按钮(例如图片应为 50,50)并居中放置在按钮上。我如何在 Swift 中执行此操作?

最佳答案

Xcode 8.3.1 • Swift 3.1

let button = UIButton(type: .custom)
let image = UIImage(named: "myimage.png")

func buttonTouchDown(_ button: UIButton) {
    print("button Touch Down")
}

override func viewDidLoad() {
    super.viewDidLoad()
    button.frame = CGRect(x: 0, y: 0 , width: 100, height: 100)
    button.backgroundColor = .clear
    button.addTarget(self, action: #selector(buttonTouchDown), for: .touchDown)
    button.setTitle("Title", for: .normal)
    button.setTitleColor(.black, for: .normal)
    button.setImage(image, for: .normal)
    button.imageEdgeInsets = UIEdgeInsetsMake(25,25,25,25)
    view.addSubview(button)
}

关于swift - 如何缩放图像并将其置于 Swift 中的 UIButton 中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27653233/

相关文章:

ios - 将 NSNotification 与 CoreData 结合使用

ios - 使用 UIView.Animate 将后退按钮移至原始位置

ios - 检测所有按钮的单一控制事件

ios - 如何使用 ARC 制作 UIBlockButton 套装?

ios - 没有在 bool 函数中获取/设置正确的返回值

iOS Facebook URL 方案无法在 Facebook 应用程序中打开页面

ios - swift 3 准备(用于 segue : ) function broken?

objective-c - 如何找到数组的索引?

swift 2.0,UITableView : Fetch index of 'checked' rows

swift - 表达式类型 UIImage 在没有更多上下文的情况下不明确