我是IOS swift的新手,过去几天我一直试图解决这个问题。我正在尝试使用从服务器下载的背景图像创建一个UIButton,并在按钮本身上添加一个文本在背景图像的顶部。
for button in data {
let btn = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
btn.frame = CGRectMake(x, y, 125, 125)
btn.backgroundColor = UIColor.greenColor()
btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
btn.setTitle(button["button_text"] as NSString, forState:UIControlState.Normal)
btn.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
btn.titleLabel?.font = UIFont(name: "Arial", size: 15)
btn.titleLabel?.textAlignment = .Center
btn.titleLabel?.numberOfLines = 5
btn.layer.borderColor = UIColor.grayColor().CGColor
btn.layer.borderWidth = 1
var item_image_url:NSString = button["button_image"] as NSString
var imgURL: NSURL = NSURL(string: item_image_url)!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
var image = UIImage(data: data)
btn.setImage(image, forState: UIControlState.Normal)
})
self.view.addSubview(btn)
}
请帮忙!提前谢谢..
KL
答案 0 :(得分:5)
我有同样的问题,并找到了解决方案。
使用BackgroundImage
而不是Image
,文字仍然可见。
所以改变:
btn.setImage(image, forState: UIControlState.Normal)
进入:
btn.setBackgroundImage(image, forState: UIControlState.Normal)
希望这也能解决你的问题。
答案 1 :(得分:0)
let imageN = UIImage(named: "imageName.jpg") as UIImage?
let button = UIButton()
button.frame = CGRectMake(10, 10, 25, 35)
button .setBackgroundImage(imageN, forState: UIControlState.Normal)
button.setTitle("Text", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)