使用swift的背景图像上的uibutton文本

0 uibutton swift

我是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)
        }
Run Code Online (Sandbox Code Playgroud)

请帮忙!提前致谢..

KL

Ren*_*ers 5

我有同样的问题,并找到了解决方案.

使用BackgroundImage而不是Image,文本将保持可见.

所以改变:

btn.setImage(image, forState: UIControlState.Normal)
Run Code Online (Sandbox Code Playgroud)

成:

btn.setBackgroundImage(image, forState: UIControlState.Normal)
Run Code Online (Sandbox Code Playgroud)

希望这也能解决你的问题.