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



我是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)
        }

请帮忙!提前谢谢..

吉隆坡

我遇到了同样的问题,并找到了解决方案。

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

所以改变:

btn.setImage(image, forState: UIControlState.Normal)

到:

btn.setBackgroundImage(image, forState: UIControlState.Normal)

希望这也能解决您的问题。

    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)

最新更新