如何从UIBarButtonItem中删除下划线? (迅速)

时间:2016-06-19 23:18:40

标签: swift uibarbuttonitem underline

我以编程方式创建了一个UIBarButtonItem,文本带有下划线。有没有办法删除下划线?

let editButton = UIButton.init(type: .Custom)

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.tabBarController?.title = "General Information"
    editButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
    editButton.addTarget(self, action: #selector(editButtonPressed(_:)), forControlEvents: .TouchUpInside)
    editButton.frame.size = CGSize(width: 60, height: 30)
    editButton.titleLabel?.adjustsFontSizeToFitWidth = true
    let barButtonItem = UIBarButtonItem.init(customView: editButton)
    self.tabBarController?.navigationItem.setRightBarButtonItem(barButtonItem, animated: true)
    updateEditButtonTitle()
    self.navigationController!.navigationItem.backBarButtonItem?.tintColor = UIColor.blackColor()
}

这是我得到的结果的图像,带有下划线。

enter image description here

这是我设置按钮文本的功能。当它被按下时,它变成一个保存按钮。

func updateEditButtonTitle() {
    if let button = self.tabBarController?.navigationItem.rightBarButtonItem?.customView as? UIButton {
        var title = ""
        editButton.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.55)
        editButton.layer.cornerRadius = 7.0
        if isInEditMode {
            title = "Save"
            editButton.setTitleColor(UIColor.redColor(), forState: .Normal)
            editButton.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.5)
            editButton.layer.cornerRadius = 7.0
            editButton.frame.size = CGSize(width: 60, height: 30)
        } else {
            editButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
            title = "Edit"
        }

        button.setTitle(title, forState: .Normal)
    }
}

1 个答案:

答案 0 :(得分:0)

试试这段代码..

var attrStr: NSMutableAttributedString = yourBtnHere.attributedTitleForState(.Normal).mutableCopy()
//or whatever the state you want
attrStr.enumerateAttributesInRange(NSMakeRange(0, attrStr.characters.count), options: .LongestEffectiveRangeNotRequired, usingBlock: {(attributes: [NSObject : AnyObject], range: NSRange, stop: Bool) -> Void in
    var mutableAttributes: [NSObject : AnyObject] = [NSObject : AnyObject](dictionary: attributes)
    mutableAttributes.removeObjectForKey(.AttributeName)
    attrStr.setAttributes(mutableAttributes, range: range)
})

使用检查员/ IB:选择您的UIButton。 显示属性检查器。 文本设置应该是Attributed。选择文本,单击喜欢的项目删除下划线设置为无。 在此处输入图像描述

Check this

但是..

让我直截了当。 Apple添加了一个辅助功能,允许用户根据需要标记带下划线的按​​钮。

你想要一种方法来打败这个功能,专门用于帮助有障碍的人使用他们的设备,当这个功能是用户必须要求的时候。

为什么?

很可能无法使用标准按钮。如果你确实找到了一种方法,Apple可能会拒绝你的应用程序,因为它会破坏一个旨在帮助残疾人的系统功能。

所以答案是:不要这样做。